父类:
package testonly;public class HelloFather {
public HelloFather(){
System.out.println("HelloFather.HelloFather()");
}
public void sayHello(){
System.out.println("hello, world!");
}
}子类:
package testonly;public class HelloSon extends HelloFather {
public HelloSon() {
}
public void execute(){
execute(super); *******************
}
public void execute(HelloFather hf){
hf.sayHello();
}
public static void main(String[] args) {
HelloSon helloSon1 = new HelloSon();
helloSon1.execute();
}
}在eclispe下,这句编译不通过,强行运行也出错。是什么原因?super可以这么用吗?
package testonly;public class HelloFather {
public HelloFather(){
System.out.println("HelloFather.HelloFather()");
}
public void sayHello(){
System.out.println("hello, world!");
}
}子类:
package testonly;public class HelloSon extends HelloFather {
public HelloSon() {
}
public void execute(){
execute(super); *******************
}
public void execute(HelloFather hf){
hf.sayHello();
}
public static void main(String[] args) {
HelloSon helloSon1 = new HelloSon();
helloSon1.execute();
}
}在eclispe下,这句编译不通过,强行运行也出错。是什么原因?super可以这么用吗?
System.out.println("this : " + this.hashCode());
System.out.println("super : " + super.hashCode());
System.out.println("this : " + this.getClass());
System.out.println("super : " + super.getClass());
它们的结果是:
this : 8187137
super : 8187137
this : class testonly.HelloSon
super : class testonly.HelloSon
也就是说,this与super指向同一个对象。可是,在子类重载了父类的某一方法时,super又的确可以调用父类中的方法。这是为什么?
System.out.println("super : " + super.hashCode());
System.out.println("this : " + this.getClass());
System.out.println("super : " + super.getClass());你把this和super去掉 你看一下,结果还是一样的 !
这里所调用的都是HelloSon这个类的hashCode的值.
问题在这一句:
execute(super); *******************
与sayHello()无关to interhanchi(艰难困苦,玉汝于成!) :
super.hashCode调用的是父类对象的hashCode()函数,如果去掉this和super,则调用的都是子类的hashCode()函数
method(super) // right ???
一个对象,是存在它的引用的,但,存在它的父类对象的引用吗?我觉得没有。因为JAVA只创建了一个对象:this。在创建一个对象时没有创建它的父类的对象!所以个人认为你的程序是有问题的。