※J.Y Chen 的個人部落格 ※

Just Follow Our Heart And We will shine!

52 瀏覽人次

【程式語言】JAVA的第八堂課 |物件導向程式設計 (車子物件複習)

Published: in JAVA by .

ch9.java

public class ch9 {
	public static void main (String[] args) {
		car mycar = new car();
		car mycar1 = new car();
		mycar.setColor("red");
		mycar.setYear(1990);
		mycar.setSpeed(0);
		mycar1.setColor("blue");
		mycar1.setSpeed(0);
		mycar1.setYear(2000);
		mycar.showCar();
		System.out.println("-//first car");
		mycar1.showCar();
		System.out.println("-//second car");
		System.out.println("-//Process//-");
		for (int i = 0 ; i < 5 ; i++){
			mycar.accelerate(20);
			mycar.showCar();
		}
		System.out.println("break.....");
		for (int j = 0 ; j < 5 ; j++){
			mycar.cbreak();
			mycar.showCar();
		}
		
		System.out.println("-----another car-----");

		mycar1.showCar();
		for (int i = 0 ; i < 6 ; i++){
			mycar1.accelerate(20);
			mycar1.showCar();
		}
		System.out.println("break.....");
		for (int j = 0 ; j < 6 ; j++){
			mycar1.cbreak();
			mycar1.showCar();
		}
		
		
	}
}

car.java


class car
{
 // data members
 private int year;
 private int speed;
 private String color;

 //member functions
 
 void showCar()
 {
   System.out.println("this "+color+" car is made in "+year+". the current spped is "+speed); 
 }
  
 void setColor(String str)
 {
   color=str;
 }  
 
 void setYear(int y)
 {
   year=y;
 }
 
 void setSpeed(int i)
 {
   speed=i;
 }
 
 void cbreak()
 {
   speed-=20; 
 } 
 void accelerate()
 {
   speed+=5; 
 }
 void accelerate(int s)
 {
   speed+=s;
 }

}

Result:

©2019 - 2024 Henry Chen