问题描述
我知道当使用父类引用来引用像这样的子类对象时,OOP中多态性的常见用法发生了:
I know that the common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object like this:
Animal animal = new Animal();
Animal dog = new Dog();
我知道多态性适用于类方法,但它是否也适用于类属性?我尝试用这个小例子来测试:
And I know that polymorphism applies on class methods, but does it also apply on class attribute? I tried to test that with this little example:
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,它取决于引用变量。
As you can see (I hope it's clear), the polymorphism works fine with the print() method, but with class attribute "name", it depends on the reference variable.
所以,我是对的吗?多态性不适用于类属性?
So, am I right? the polymorphism doesn't apply on class attributes?
推荐答案
扩展类时,方法被覆盖,但字段被隐藏。动态分派适用于方法,但不适用于字段。为什么语言设计如此,天知道为什么。
When you extend a class, methods are overriden, but fields are hidden. Dynamic dispatch works for methods, but not for fields. Why is the language designed so, god knows why.
这篇关于多态是否适用于Java中的类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!