this类变量

1.this;

2.类变量、类方法

3.四大特征

this属于一个具体的对象,而不是属于一个类,创建一个对象的时候,this自动就带过来了,就像上帝创造一个人的时候,自然把我这个词赋予这个人。

例子:

public class Person {

int age;

String name;

Dog dog;//引用类型,

public Person(int gae,String name,Dog dog){

this.age=age;

this.name=name;

this.dog=dog;

}

public void show(){

System.out.println("名字是:"+this.name);

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Dog dog1=new Dog(3,"旺财");

Person p1=new Person(23,"小王",dog1);

p1.show();

p1.dog.ShowDog();//调用狗这个类里面的函数

}

}

class Dog{

int age;

String name;

public Dog(int age,String name){

this.age=age;

this.name=name;

}

public void ShowDog(){

System.out.println("狗名叫:"+this.name);//显示狗的名字

}

}

输出结果:

内存如图:

注意this不能再类定义的外部使用,只能在类定义的方法中使用。

 

静态变量(类变量):

例题:有一群小孩在玩堆雪人,不时有新的小孩加入,请问如何知道现在有多少人在玩?

解析:在设计一个int total表示总人数,在创建啊一个小孩类时,把total加一,并且total所有对象共享,如图:

 

程序如下:

public class Person {

int age;

String name;

public Person(int gae,String name){

this.age=age;

this.name=name;

}

public void show(){

System.out.println("名字是:"+this.name);

}

public static void main(String[] args) {

Person p1=new Person(23,"小王");

p1.show();

Child ch1=new Child(3,"妞妞");

ch1.JoinGame();

Child ch2=new Child(4,"李丽");

ch2.JoinGame();

Child ch3=new Child(4,"连连");

ch3.JoinGame();

System.out.println("总共有"+ch3.total+"个人参加游戏");

}

}

//定义小孩类

class Child{

int age;

String name;

static int total=0;//静态变量,因此它可以被任何一个对象访问

public Child(int age,String name){//child的构造方法

this.age=age;

this.name=name;

}

public void JoinGame(){

total++;

System.out.println("有一个小孩加入游戏。");

}

}

输出结果:

猜你喜欢

转载自blog.csdn.net/hml666888/article/details/81211961