1 public class demo1 {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         Dog dog1=new Dog(5,"小白");
 6         Person p1=new Person(dog1,25,"Leng");
 7         p1.ShowInfo();
 8         p1.dog.ShowInfo();
 9 
10     }
11 
12 }
13 //定义一个人类
14 class Dog
15 {
16     int age;
17     String name;
18     public Dog(int age,String name)
19     {
20         this.age=age;
21         this.name=name;
22     }
23     public void ShowInfo()
24     {
25         System.out.println("狗的名字是"+name);
26     }
27 }
28 class Person
29 {
30 int age;
31 String name;
32 Dog dog;//引用类型
33 //写本类的一个构造方法
34 public Person(Dog dog,int age,String name)
35 {
36     this.age=age;
37     this.name=name;
38     this.dog=dog;
39 }
40 public void ShowInfo()
41 {
42     System.out.println("这个人的名字是"+name);
43 }
44 }

java虚拟机会给每个对象分配this ,代表当前对象。

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