如何理解java中的super
我遇到了一个让我困惑的问题,它是关键字“super”,我的测试代码如下:如何理解java中的super,java,properties,super,Java,Properties,Super,我遇到了一个让我困惑的问题,它是关键字“super”,我的测试代码如下: package test; public class Parent { private String name; public Parent(){ this.name = "parent"; } public String getName() { return name; } public void setName(String
package test;
public class Parent {
private String name;
public Parent(){
this.name = "parent";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void showName(){
System.out.println(this.name);
}
}
public class Child extends Parent{
public Child(){
this.setName("Child");
}
public void showName(){
System.out.println(super.getClass().toString());
System.out.println(super.toString());
super.showName();
System.out.println(super.getName());
}
}
public class Test {
public static void main(String[] args) {
Child d = new Child();
d.showName();
}
}
class test.Child
test.Child@2207d8bb
Child
Child
所以结果是这样的:
package test;
public class Parent {
private String name;
public Parent(){
this.name = "parent";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void showName(){
System.out.println(this.name);
}
}
public class Child extends Parent{
public Child(){
this.setName("Child");
}
public void showName(){
System.out.println(super.getClass().toString());
System.out.println(super.toString());
super.showName();
System.out.println(super.getName());
}
}
public class Test {
public static void main(String[] args) {
Child d = new Child();
d.showName();
}
}
class test.Child
test.Child@2207d8bb
Child
Child
我对“super”的理解是,它是对当前实例的父实例的引用,所以我期望的输出类似于“parent”,从结果来看,我错了,它类似于当前实例调用父方法,“super”不是父实例,我的理解对吗?有没有一种方法可以让父实例只初始化子类
我对“super”的理解是,它是对当前实例的父实例的引用
不-没有父实例这样的东西。当您创建一个实例时,只创建了一个对象—一个Child实例,它也从父对象继承所有字段和方法
super有两种使用方式:
引用方法的超类实现,通常是在子类中重写该方法时。这就是您在Child.showName中所做的操作-它调用Parent.showName,但是在同一个实例上,因为只有一个实例
从子类构造函数调用超类构造函数
从javadocs中,getClass返回对象的运行时类
对象的运行时类是Child
由于没有重写getClass,所以不能重写,因为它是最终的,所以super.getClass的行为与getClass完全相同。调用对象类的getClass方法
如果要打印父对象,请调用getClass.getSuperclass您使用了使用子对象调用的四条打印语句: System.out.printlsuper.getClass.toString; 由于getClass是最终方法,因此它不能被重写,因此当您调用super.getClass时,您实际上调用了对象类的getClass,它返回实际调用对象的类的名称 System.out.printlnsuper.toString; 这里再次调用对象类的toString方法,该方法返回 getClass.getName+@+Integer.toHexStringhashCode; 但是,如果在父类中重写此方法,则肯定会执行该版本 super.showName; 此方法返回Child。。。。原因如下:创建子类的对象时,构造函数按如下方式运行- 公共儿童{ super;//编译器会隐式调用此函数,即使您没有编写此函数 这个.setNameChild; } 因此,以下操作将发生-1。调用父类的构造函数,该构造函数将“name”设置为“Parent”。2.子类的构造函数现在用“Child”覆盖该值。 因此,实例变量“name”的值是“Child” System.out.printlnsuper.getName; 如第3点所述,这里只有一个对象和一个实例变量'name',其值为'Child' } 输出将是 动物:吃 狗:吃 动物:吃
第三行是印刷动物:吃,因为我们称之为super.eat。如果我们称之为this.eat,它将打印为dog:eat。没有解决实际问题。