多态是否适用于Java中的类属性?我知道当使用父类引用来引用子类对象时,OOP中多态性的常见用法是这样的:Animal animal = new Animal();Animal dog = new Dog();我知道多态性适用于类方法,但它是否也适用于类属性?我尝试用这个小例子来测试它:public class Main{
public static void main(String args[]){
Animal animal = new Animal();
Animal dog1 = new Dog();
Dog dog2 = new Dog();
System.out.println("Animal object name: " + animal.name);
System.out.println("Dog1 object name: "+dog1.name);
System.out.println("Dog2 object name: " + dog2.name);
animal.print();
dog1.print();
dog2.print();
}}class Animal{
String name = "Animal";
public void print(){
System.out.println("I am an: "+name);
}}class Dog extends Animal{
String name = "Dog";
public void print(){
System.out.println("I am a: "+name);
}}这是输出:Animal object name: AnimalDog1 object name: AnimalDog2 object name: DogI am an: AnimalI am a: DogI am a: Dog正如您所看到的(我希望很清楚),多态性与print()方法一起正常工作,但是对于class属性“name”,它取决于引用变量。所以,我是对的吗?多态性不适用于类属性?
添加回答
举报
0/150
提交
取消