输出是十么?

package cn.galc.test;

class Base
{
    private int i =2;
    public Base()
    {
        System.out.println(this.i);
        this.display();
        System.out.println(this.getClass());
    }
    public void display()
    {
        System.out.println(i);
    }
}

class Derived extends Base
{
    private int i =22;
    public Derived()
    {
        i=222;
    }
    public void display()
    {
        System.out.println(i);
    }
}
public class Test {
    public static void main(String args[]) {     
        new Derived();
    }
}

2
0
class cn.galc.test.Derived

解答:

当变量的编译时类型和运行时类型不同时,通过该变量访问他引用的对象的实例变量时,该实例变量的值由声明该变量的类型决定。

但通过该变量调用他引用的 变量的实例方法时,该方法行为将由它实际所阴阳的对象来决定。

因此,当程序访问this.i时, 将会访问Base类中定义的i实例变量,也就是输出2.但执行this.display()代码时,则实际表现出Derived对象的行为,也就是输出Derived对象的i实例变量,即0.

 

package cn.galc.test;

class Animal
{
    private String desc;
    public Animal()
    {
        this.desc = getDesc(); //2
    }
    public String getDesc()
    {
        return "Animal";
    }
    public String toString()
    {
        return desc;
    }
}

class Wolf extends Animal
{
    private String name;
    private double weight;
    public Wolf(String name, double weight)
    {
        this.name = name;  //3
        this.weight = weight;
    }
    
    @Override
    public String getDesc()
    {
        return "Wolf[name=" +name + ",weight=" +weight +"]";
    }
}

public class Test {
    public static void main(String args[]) {     
         System.out.println(new Wolf("huitailang", 32.1)); //1
    }
}

Wolf[name=null,weight=0.0]

解答:

由于父类override子类方法,所以调用父类。但此时父类的 //3处尚未得到执行。

 

package cn.galc.test;
class Base
{
    int count =2;
    public void display()
    {
        System.out.println(this.count);
    }
}
class Derived extends Base
{
    int count = 20;
    @Override
    public void display()
    {
        System.out.println(this.count);
    } 
}

public class Test {
    public static void main(String args[]) {     
         Base b = new Base();
         System.out.println(b.count);  //2
         b.display(); //2
         Derived d = new Derived();
         System.out.println(d.count); //20
         d.display(); //20
         
         Base bd = new Derived();
         System.out.println(bd.count); //20
         bd.display(); //20
         
         Base b2d = d;
         System.out.println(b2d.count); //20
    }
}

 

2 2 20 20 2  20 2

当通过这些变量调用方法时,方法的行为总是表现炒他们实际类型的行为;但如果通过这些变量来访问他们所指向对象的实例变量,这些实例变量的值总是表现出声明这些变量所用类型的行为。由此可见,java继承在处理成员变量和方法时是有区别的。

 

你可能感兴趣的:(输出)