多态性是否适用于 Java 中的类属性? [英] Does polymorphism apply on class attributes in Java?

查看:33
本文介绍了多态性是否适用于 Java 中的类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在 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 中的类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆