Java Class method
Java Class Method
Khai báo Method
accessModifier returnType methodName(parameterList) {
// body of method
}Ví dụ:
public class Car {
// Attribute
private String color;
private int maxSpeed;
// Constructor
public Car(String color, int maxSpeed) {
this.color = color;
this.maxSpeed = maxSpeed;
}
// Method để 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();
}
}Truyền tham số vào Method
Ví dụ:
Method trả về giá trị
Ví dụ:
Method Overloading
Ví dụ:
Bài tập thực hành
Tạo lớp Calculator
Method Overloading
Last updated