Java是一種面向對象的編程語言,它強調數據和行為被組織成對象。在Java中,每個對象都由屬性和行為組成。屬性表示對象的狀態,而行為則表示對象可以執行的操作。以下是Java中屬性和行為的一些舉例:
public class Car { private String make; private String model; private int year; private double price; public Car(String make, String model, int year, double price) { this.make = make; this.model = model; this.year = year; this.price = price; } public String getMake() { return make; } public String getModel() { return model; } public int getYear() { return year; } public double getPrice() { return price; } public void setMake(String make) { this.make = make; } public void setModel(String model) { this.model = model; } public void setYear(int year) { this.year = year; } public void setPrice(double price) { this.price = price; } public void start() { System.out.println("The " + make + " " + model + " started."); } public void stop() { System.out.println("The " + make + " " + model + " stopped."); } }
以上是一個汽車類的示例,它有四個屬性:make、model、year和price。它還有兩個行為:start和stop方法。start方法會輸出汽車已經啟動的信息,stop方法會輸出汽車已經停止的信息。
以下是汽車類的示例代碼的使用:
public static void main(String[] args) { Car myCar = new Car("Toyota", "Camry", 2020, 25000.0); System.out.println("My car is a " + myCar.getYear() + " " + myCar.getMake() + " " + myCar.getModel() + " that costs " + myCar.getPrice() + " dollars."); myCar.start(); myCar.stop(); }
以上代碼會輸出以下信息:
My car is a 2020 Toyota Camry that costs 25000.0 dollars. The Toyota Camry started. The Toyota Camry stopped.
在這個示例中,我們可以看到屬性和行為是如何被組合在一起的。我的汽車對象有make、model、year和price屬性,并且可以執行start和stop方法這兩個行為。