Nhập môn Lập trình Hướng đối tượng với Java
Sani Yusuf
Lead Software Engineering Content Developer

public có thể truy cập qua instance đối tượngclass Car { // Public property public String color;// Public constructor public Car(String color){ this.color = color; } }
public class Main {
// main method
public static void main(String[] args) {
Car myCar = new Car("brown");
// Có thể truy cập thành viên public
// từ instance đối tượng
System.out.println(
myCar.color); // Brown
}
}
private có thể truy cập bởi instance đối tượngprivate chỉ dùng trong nội bộ lớp// Car class class Car { public String color;// Private properties private String model;public Car(String color){ this.color = color; } }
// Main class
public class Main {
// main method
public static void main(String[] args) {
Car myCar = new Car("brown");
// Gọi thuộc tính private gây lỗi
System.out.println(
myCar.model); // Java compilation error
}
}
// Car class
class Car {
public String color;
private String model;
public Car(String color){
this.color = color;
}
// Public method
public String getModel(){
return this.model;
}
}
class Car {// Private method, "calculateSpeed" can only be used within "Car" class private calculateSpeed(){ // Trademarked formula code } public int getSpeed(){ // "calculateSpeed" can be used anywhere within "Car" class return this.calculateSpeed(); } }
static có thể truy cập không cần tạo đối tượng
// Formula class
static class Formula {
// Method for calculating square
static int getSquare(int number) {
return number * number;
}
}
// Main class
public class Main {
public static void
main(String[] args) {
// Có thể dùng "getSquare"
// mà không cần đối tượng
System.out.println(
Formula.getSquare(5)); // 25
}
}
public, private, staticstatic cho phép dùng lớp mà không cần tạo instanceNhập môn Lập trình Hướng đối tượng với Java