Java Constructor
Java Constructor
Khai báo Constructor
Cú pháp:
class ClassName {
// Constructor
ClassName(parameterList) {
// body of constructor
}
}Ví dụ:
public class Car {
private String color;
private int maxSpeed;
// Constructor
public Car(String color, int maxSpeed) {
this.color = color;
this.maxSpeed = maxSpeed;
}
// Phương thức để hiển thị thông tin của ô tô
public void displayInfo() {
System.out.println("Color: " + color);
System.out.println("Max Speed: " + maxSpeed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
// Tạo một đối tượng ô tô từ lớp Car
Car myCar = new Car("Red", 200);
// Gọi phương thức hiển thị thông tin của ô tô
myCar.displayInfo();
}
}Constructor Mặc Định
Ví dụ:
Constructor Overloading
Ví dụ:
Bài tập thực hành
Tạo lớp Person
Tạo lớp BankAccount
Bài tập thêm
Last updated