把“类”分为主导者类和工具人类;
主导者类的成员变量可以是工具人类类型;
public class Pet {
private String type;
public String name;
public Pet(String type){
this.type = type;
}
public String getType() {
return type;
}
}
public class Dog extends Pet{
public Dog(String name){
// 继承必须调用父类的构造方法?
super("Dog");
this.name = name;
}
public void eat(){
System.out.println("狗吃骨头");
}
}
Pet 类作为 Person 类的第三个私有成员变量的类型;
pet 变量是 Person 的【类成员变量】;
在 Person 类的内部,类成员变量的作用就是调用它自己的属性或者成员方法;
public class Person {
private String name;
private int age;
// 类作为成员变量属性 → 称该变量为类成员变量
private Pet pet;
public Person(String name, int age, Pet pet) {
this.name = name;
this.age = age;
this.pet = pet;
}
// 调用【类成员变量】的方法或属性
public void introduce(){
System.out.println("my name is " + this.name + ", my age is " + this.age + ", my pet's name is " + this.pet.name);
// 想要访问类成员变量的私有属性 → 用 getXxx 方法
System.out.println("my pet's type is " + this.pet.getType());
}
}
public class test {
public static void main(String[] args) {
Pet erHa = new Dog("哈士奇");
Person p = new Person("陈志海",24,erHa);
p.introduce();
}
}