1. 程式人生 > 實用技巧 >JAVA類和物件;類的定義

JAVA類和物件;類的定義

類的定義

public class People {
//1. 屬性 -> 例項變數/成員變數
private String name;
private int age;
//3. 建構函式 初始化 成員變數
public People(String name,int age){// this 指向當前物件
this.name = name;
this.age = age;
}

//2. 行為 - > 例項方法/成員方法
public void eat(){
System.out.println(this.name + "吃飯");

}
public void hitBall(){
System.out.println(this.name + "打球");
}
}

//呼叫

public class Test {
    public static void main(String[] agrs){
        //例項化
      People p=new People("fg",38);
//行為
      p.eat();
      p.hitball();
    }
}

例題

public class Car {
    //屬性
    String name;
    String color;
    String carid;
    //例項化;
    public Car(String name,String color,String carid){
        this.name = name;
        this.carid=carid;
        this.color=color;
    }
    //啟動方法
    void start(){
        System.out.println(name +" "+ carid +" "+color+" "+"start");
    }
    //停止方法
    void stop(){
        System.out.println(name +" "+ carid +" "+color+" "+"stop");
    }
}

//呼叫

public class Test {
    public static void main(String[] agrs){
        //例項化
        Car car1=new Car("AE86","黃色","sb666");
        Car car2=new Car("benz","深海色","fgnb222");
        //行為
        car1.start();
        car2.start();
        car1.stop();
        car2.stop();
    }
}

執行結果