天天看點

靜态變量,構造方法,普通方法,私有方法

1.建立一個Girl.class,裡面沒有psvm可以運作

package com.animal;

public class Girl {

    // 靜态變量 全部大寫 下劃線隔開多個單詞

    public static String BOY_FRIEND_NAME;
    public static int BOY_FRIEND_AGE;

    // 屬性必須定義成private
    // 按住shift+F6,選擇name,下面是以參數都會改變,稱為setter

    private int age;
    private String name;

    // 構造方法

    public Girl(){ }
    public Girl(String name, int age){
        this.age = age;
        // this表示誰調用就跟誰
        this.name = name;
    }

    // 普通方法
    public void meet(String boyName){
        // 先化妝
        makeUp();
        System.out.println(boyName +"覺得"+ this.name +"她好美……");
    }

    // 私有方法
    private void makeUp(){
        System.out.println("今天化了唐朝妝面");
    }

    // 還有一些方法
    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){   // get方法不需要參數
        if(age > 18){
            // 如果年齡大于18則輸出18
            return 18;
        }
        return this.age;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}
           

2.建立Test類,調用Girl裡的類,進行指派

package com.animal;

public class Tset1 {
    public static void main(String[] args) {
        Girl zhenzhen = new Girl();
        zhenzhen.setAge(18);
        zhenzhen.setName("zhenzhen");
        zhenzhen.meet("嫦娥");
        Girl lianlian = new Girl("lianlian",16);
        lianlian.meet("悟空");
    }

}