子类父类构造方法的问题

来源:百度知道 编辑:UC知道 时间:2024/06/08 14:02:59
class Base{ // 程序4-12
int x=100;
void print( ){
System.out.println("当前类为 "+this.getClass().getName());
System.out.println("对象的x= "+this. x );
}
}
class Derived extends Base{
int x=2;
Derived(int a){
this.x=a;
}
void print(){
System.out.println("当前类为 "+this.getClass().getName());
System.out.println("对象的x= "+this. x );
}
} class confusions{
public static void main(String [] args){
Base obj=new Derived(7 );
obj.print();
System.out.println("当前类为 "+obj.getClass().getName());
System.out.println("对象的x= "+obj.x);
}
}
谁能帮我解释一下为什么运行结果是
当前类为 Derived
对象的x= 7
当前类为 Derived
对象的x= 100
特别是为什么第二个x会是100呢???
谢谢哈

这就是JAVA的多态性.
因为 Base obj = new Derived(7);的时候,new出来的是Base的实例对象,
而new Derived(7)调用的是Derived类的构造方法,使a的值变成了7,
所以执行obj.print()的时候实际是执行的Derived类的print()方法;

System.out.println("对象的x= "+obj.x); 因为obj是Base类的实例对象,所以
obj.x是Base类的x的值所以是:100;

Base obj=new Derived(7 );
父类应用指向子类对象,这是明显的多态..
在java中继承中,方法是可以被覆盖的,但是属性并没有这个特征。因为obj是Base的应用,所以运行结果就是100了