Java中属性为什么不是多态的

发布于:2025-08-31 ⋅ 阅读:(23) ⋅ 点赞:(0)
package animal;

public class Animal {
    public String name = "Animal";
    public void eat () {
        System.out.println("Animal is eating");
    }
}
package animal;


public class Cat extends Animal {
    public void eat () {
        System.out.println("Cat is eating");

    }
}
package animal;

public class Dog extends Animal {
    public String name = "Dog";
    public void eat () {
        System.out.println("Dog is eating.");

    }
}

import animal.Animal;
import animal.Cat;
import animal.Dog;


public class main {
    public static void main (String[] args) {
        System.out.println("Hello, world!");


        Animal c = new Cat();
        c.eat();
        System.out.println(c.name);

        Animal d = new Dog();
        d.eat();
        System.out.println(d.name);

        Animal a = new Animal();



        System.out.println(System.identityHashCode(c.name) == System.identityHashCode(d.name));
        System.out.println(System.identityHashCode(c.name) == System.identityHashCode(a.name));

        System.out.println(System.identityHashCode(hehe()));
    }

    public static String hehe () {
        return "hehe";
    }
}

输出:

yuzhou@yudeMac-mini molyphism % javac main.java
yuzhou@yudeMac-mini molyphism % java main      
Hello, world!
Cat is eating
Animal
Dog is eating.
Animal
true
true
1311053135

死活不理解为什么java属性不是多态的,从存储角度来看,运行如下两行代码,发现三个变量的内存地址相同,脑补应该是存在了某个公共的地方。但对象的方法是多态的,就是调用父类对象的方法,实际是运行的子类的同名方法,这个自己脑补吧,哈哈

System.out.println(System.identityHashCode(c.name) == System.identityHashCode(d.name));

System.out.println(System.identityHashCode(c.name) == System.identityHashCode(a.name));