多态性是否适用于 Java 中的类属性?
2022-09-03 04:36:33
我知道,当父类引用用于引用子类对象时,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: Animal
Dog1 object name: Animal
Dog2 object name: Dog
I am an: Animal
I am a: Dog
I am a: Dog
正如你所看到的(我希望它是清楚的),多态性与print()方法一起工作得很好,但是对于类属性“name”,它取决于引用变量。
那么,我说的对吗?多态性不适用于类属性?