天天看點

Java文法-類名稱作成員變量類型-類成員變量

把“類”分為主導者類和工具人類;

主導者類的成員變量可以是工具人類類型;

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();
    }
}