this 、静态变量

/*
作者:qingfeng
日期:2017/2/18
功能:this,静态变量(类变量)
*/
class Demo3_2
{
    public static void main(String args[])
    {
        Dog dog1 = new Dog(1, "黄黄");

        Person p1 = new Person(dog1, 30, "周杰伦");
        p1.showInfo();
        
        Person p2 = new Person(dog1, 22,  "关晓彤");
        p2.showInfo();

        System.out.println(p2.total);//访问静态变量:类名.静态变量 或者 对象名.静态变量

        p1.dog.showInfo();
        
    }
}
class Person
{
    int age;
    String name;
    Dog dog; //引用类型

    static int total = 0; //静态变量(类变量)静态变量:所有对象共有

    public Person(Dog dog, int age, String name){
        this.age = age;//this属于具体的对象
        this.name = name;
        this.dog = dog;
    }
    public void showInfo(){
        total ++;
        System.out.println("人名为"+this.name);
    }
}

class Dog
{
    int age;
    String name;
    public Dog(int age, String name){
        this.age = age;//this属于具体的对象
        this.name = name;
    }
    public void showInfo(){
        System.out.println("狗名为"+this.name);
    }
}

原文地址:https://www.cnblogs.com/qingfengzhuimeng/p/6413466.html