java - super 和 ((parent)this) 之间的区别?

标签 java

super 关键词相关疑问。

class Parent{
    int x=40;
    void show()
    {
        System.out.println("Parent");
    }
}

class Child extends Parent
{   int x=20;
    void show()      //method overriding has been done
    {

        System.out.println(super.x); // prints parent data member
        System.out.println(((Parent)this).x); /*same output as previous statement which means super is similar to (Parent)this*/ 
        System.out.println("child");
        super.show();  // invokes parent show() method  
        ((Parent)this).show(); //Doesnt invoke parent show() method.Why?
    }

public static void main(String s[])
{ 
    Child c1=new Child(); //Child class object
    c1.show();  
}}

所以,System.out.println(super.x)System.out.println(((Parent)this).x)打印相同的值。所以如果 super.show()调用父类show()方法那么为什么是((Parent)this).show();无法调用家长show() ?请对此作出适当的解释。

最佳答案

构造函数链 在 Java 中,关键字 this 表示当前对象,当一个类扩展另一个类时,其父类(super class)引用变量可能会保存代码中的子类引用变量,即 ((Parent)this).x

super关键字用于直接调用父类(super class)构造函数及其变量。

同时,当super类变量保存子类对象时,当我们使用super时,它引用同一个对象。

How to call one constructor from another constructor in Java or What is Constructor Chaining in Java is one of the tricky questions in Java interviews. Well, you can use this keyword to call one constructor from another constructor of the same class if you want to call a constructor from based class or super class then you can use super keyword. Calling one constructor from other is called Constructor chaining in Java. Constructors can call each other automatically or explicitly using this() and super() keywords. this() denotes a no-argument constructor of the same class and super() denotes a no argument or default constructor of parent class. Also having multiple constructors in the same class is known as constructor overloading in Java.

了解更多:http://www.java67.com/2012/12/how-constructor-chaining-works-in-java.html#ixzz4bJ5C069o

关于java - super 和 ((parent)this) 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42787226/

相关文章:

java.lang.NoSuchMethodError : org. openqa.selenium.support.ui.Wait.until(Lcom/google/common/base/Function;)使用selenium-server-standalone-3.12.0

java - 从 servlet 到达 xml

java - 使用 Java 应用程序客户端在 WCF 客户端中使用 STE 实体

java - java中如何获取项目名称?

java.lang.异常 : No Certificate file specified or invalid file format

延迟后的 Java EJB 调用方法

java - 重用 StringBuilder 和 ArrayIndexOutOfBoundsException

java - 如何从导航组件中的子 fragment 访问父 fragment 的 View

java - 我如何在 Java 中获取 XML 元素的兄弟元素(使用 DOM 解析器)?

java - iText Android - 向现有 PDF 添加文本