package sample2.com; // Constructor與Class同名 // Constructor不需要任何回傳值 public class Car { private int num; private double gas; public Car(){// 沒有參數的建構子 num = 0; gas = 0.0; System.out.println("生產了汽車"); } public Car(int n,double g){// 兩個參數的建構子 num = n; gas = g; System.out.println("生產了汽車" + num + ",汽油量"+ gas + "的汽車" ); } public void show(){ System.out.println("車號是" + num ); System.out.println("汽油量是" + gas); } public static void main(String[] args) { // TODO Auto-generated method stub Car car1 = new Car();// 建立物件時會自動呼叫沒有參數的建構子 car1.show(); Car car2 = new Car(5678,20.5);// 建立物件時呼叫兩個參數的建構子 car2.show(); } }
沒有留言:
張貼留言