多态

class Mammal{}

class Dog extends Mammal {}

class Cat extends Mammal{}

public class TestCast

{

public static void main(String args[])

{

Mammal m;

Dog d=new Dog();

Cat c=new Cat();

m=d;

//d=m;

d=(Dog)m;

//d=c;

//c=(Cat)m;

}

}

通过运行结果我们可以知道:

m=d;d=(Dog)m可以赋值。可以编译,

 

但是在没有m=d;时仅有d=(Dog)m将不能赋值。因为m没有进行初始化。

d=m不可以赋值。不能编译

 

d=c不可以赋值。不能编译

 

m=d;C=(Cat)m;不可以赋值。可以编译但是不可以运行。m=c;C=(Cat)m;才能运行

 

源代码:

public class ParentChildTest {

public static void main(String[] args) {

Parent parent=new Parent();

parent.printValue();

Child child=new Child();

child.printValue();

parent=child;

parent.printValue();

parent.myValue++;

parent.printValue();

((Child)parent).myValue++;

parent.printValue();

}

}

class Parent{

public int myValue=100;

public void printValue() {

System.out.println("Parent.printValue(),myValue="+myValue);

}

}

class Child extends Parent{

public int myValue=200;

public void printValue() {

System.out.println("Child.printValue(),myValue="+myValue);

}

}

实验内容:

1) 运行课件中的例题ParentChildTest.java,回答下列问题:

a) 左边的程序运行结果是什么?

 

b) 你如何解释会得到这样的输出?

答:当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时, 到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象 是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方 法。

注意:子类不能引用父类的对象

 

c) 计算机是不会出错的,之所以得到这样的运行结果也是有原因的,那么从这 些运行结果中,你能总结出Java的哪些语法特性?

答:

(1)如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类 的 字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子 类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问 它。

(2)如果子类被当作父类使用,则通过子类访问的字段是父类的!

原文地址:https://www.cnblogs.com/amiee/p/4965862.html