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

Just Follow Our Heart And We will shine!

40 瀏覽人次

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

Published: in JAVA by .

ch9.java

public class ch9
{

 public static void main(String[] aru)
 {
    car mycar=new car(1990,"blue",0);
    car mycar1=new car(2020,"red",0);
    car mycar2=new car(2020,"yellow",0);
    
	mycar.showCar();
    mycar1.showCar();
    mycar2.showCar();
    mycar2.copy(mycar);
    mycar2.showCar();
    /*
    int[] ar;
    ar=new int[10];
    car[] carAr;
    carAr=new car[10];
    for(int i=0;i<10;i++)
    {
       carAr[i]=new car(2020,"Green",0);
       carAr[i].showCar();
    }
	*/
	
    mycar.accelerate(185);
    mycar1.accelerate(285);
    if(mycar.isFasterThan(mycar1))
     System.out.println(mycar.getID()+" is faster");
    else
      System.out.println(mycar1.getID()+" is faster");
 }
}

car.java

class car
{
 // data members
 private int year;
 private int speed;
 private String color;
 private String ID;
 private static int counter=0; 
 //member functions
 car()
 {
   System.out.println("car is created!!");
   speed=0;
   year=2020;
 } 
  
 car(int y, String c, int b)
 {
   speed=b;
   year=y;
   color=c;
   ID="IM00"+(counter+1);
   counter++;
 } 



 car(String c)
 {
   speed=0;
   year=2020;
   color=c;
 } 

  
 void showCar()
 {
   System.out.println("this "+ID+" car is made in "+year+". the current speed is "+speed); 
 }
  
 String getColor()
 {
   return color;
 }
 int getYear()
 {
   return year;
 }
 String getID()
 {
   return ID;
 }  



 void copy(car c)
 {
   color=c.getColor();
   year=c.getYear();
   ID=c.getID(); 
   speed = c.getSpeed();
  
 }  
 
 int getSpeed () {
	 return speed;
 }

 void setColor(String str)
 {
   color=str;
 }  
  

 void setYear(int y)
 {
   year=y;
 }
 
 void setSpeed(int i)
 {
   speed=i;
 }
 
 int cbreak()
 {
   speed-=5; 
   return speed;
 } 
 int accelerate()
 {
   speed+=5; 
   return speed;
 }
 void accelerate(int s)
 {
   speed+=s;
 }
 
 Boolean isFasterThan(car c) {
	 if (c.getSpeed() > getSpeed()) {
		 return false;
	 }
	 else {
		 return true;
	 }
 }

}

Result:

©2019 - 2024 Henry Chen