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/