Một chương trình Java đơn lẻ chứa hai hoặc nhiều class, điều này có thể thực hiện theo hai cách trong Java.
Hai cách triển khai Multiple Classes trong một Java Program
- Nested Classes
- Multiple non-nested classes
Compiler xử lý Multiple non-nested classes như thế nào
Trong ví dụ dưới, java program chứa hai class, một tên Computer và một tên Laptop. Cả hai class có constructor riêng và một method. Trong main method, chúng ta có thể tạo object của hai class và gọi methods của chúng.
Ví dụ
public class Computer {
Computer() {
System.out.println("Constructor of Computer class.");
}
void computer_method() {
System.out.println("Power gone! Shut down your PC soon...");
}
public static void main(String[] args) {
Computer c = new Computer();
Laptop l = new Laptop();
c.computer_method();
l.laptop_method();
}
}
class Laptop {
Laptop() {
System.out.println("Constructor of Laptop class.");
}
void laptop_method() {
System.out.println("99% Battery available.");
}
}Khi compile chương trình trên, hai file .class sẽ được tạo là Computer.class và Laptop.class. Điều này có lợi thế là chúng ta có thể reuse file .class ở dự án khác không cần compile lại code. Tóm lại, số file .class tạo ra sẽ bằng số class trong code. Chúng ta có thể tạo bao nhiêu class tùy ý nhưng viết nhiều class trong một file không khuyến khích vì làm code khó đọc, thay vào đó có thể tạo file riêng cho mỗi class.
Kết quả
Constructor of Computer class. Constructor of Laptop class. Power gone! Shut down your PC soon... 99% Battery available.
Compiler xử lý Nested classes như thế nào
Khi main class được compile có nhiều inner classes, compiler sinh ra file .class riêng cho từng inner class.
Ví dụ
// Main class
public class Main {
class Test1 { // Inner class Test1
}
class Test2 { // Inner class Test2
}
public static void main(String [] args) {
new Object() { // Anonymous inner class 1
};
new Object() { // Anonymous inner class 2
};
System.out.println("Welcome to Tutorials Point");
}
}Trong chương trình trên, chúng ta có Main class có bốn inner classes Test1, Test2, Anonymous inner class 1 và Anonymous inner class 2. Khi compile class này, nó sẽ sinh ra các file class sau.
Main.class
Main$Test1.class
Main$Test2.class
Main$1.class
Main$2.class
Kết quả
Welcome to Tutorials Point