java類與對象,用程序解釋

//第一個
1
public class Cardemo{ 2 public static void main(String[] args){ 3 Car carwind = new Car(60,"red","west"); 4 carwind.speed = 60; 5 carwind.color = "red"; 6 carwind.direction = "west"; 7 8 System.out.println("The speed of car is " + carwind.speed); 9 System.out.println("The color of car is " + carwind.color); 10 System.out.println("The direction of car is " + carwind.direction); 11 } 12 } 13 class Car{ 14 //定義四個成員變量(屬性) 15 int speed; 16 String color; 17 String name; 18 String direction; 19 }

第二個this

public class Cardemo{
    public static void main(String[] args){
        Car carwind = new Car(60,"red","west"); //建立一個Car類的引用
        carwind.speed = 60;
        carwind.color = "red";
        carwind.direction = "west";
        
        System.out.println("The speed of car is " + carwind.speed);
        System.out.println("The color of car is " + carwind.color);
        System.out.println("The direction of car is " + carwind.direction);
        carwind.drivecar();
        carwind.speedup(5);
        System.out.println("The speed of car is " + carwind.speed);
        
    }
}
class Car{
    //定義四個成員變量(屬性)
    int speed;
    String color;
    String name;
    String direction;
    
    Car(int speed, String color, String direction){
        this.speed = speed;
        this.color = color;
        this.direction = direction;
    }
    
    public void drivecar(){
        System.out.println("here we go!");
    }
    public void speedup(int aspeed){
        this.speed = speed + aspeed;
    }
}
相關文章
相關標籤/搜索