Java对象访问 类的静态变量

Java类的静态变量用对象和类名都能访问,一般用类名,但如果用对象来访问静态变量呢,有何种效果?

测试一下:

package JavaTest;

public class test{
    public static void main(String[] args)
    {
        Horse h=new Horse();
        Horse h2=new Horse();
        System.out.println(h.count);//1
        System.out.println(h2.count);//1
        h.count=3;
        System.out.println(h.count);//3
        System.out.println(h2.count);//3
        System.out.println(Horse.count);//3
        System.out.println(Animal.count);//3
    }
    
}

class Animal
{
    public static int count=1;
    public String name;
}

class Horse extends Animal
{
}

由此可见,单个对象可以改变公共的静态变量的值,还可以改变从父类继承过来的静态变量的值。

原文地址:https://www.cnblogs.com/aaronhoo/p/5830880.html