Nested class trong java với ví dụ cụ thể

Một class nằm trong một class khác được gọi là Nested class. Nested class cho phép bạn nhóm các class chỉ được sử dụng tại một nơi duy nhất, làm tăng tính đóng gói, code dễ đọc và bảo trì hơn.

  • Phạm vi của nested class được bao bởi class chứa chứa nó.
  • Nested class cũng là một thành viên của class chứa nó.
  • Nested class có thể truy cập các thành viên khác của class chứa nó kể cả các thành private. Tuy nhiên điều ngược lại là không đúng, class chứa nó sẽ không thể truy cập được các thành viêncủa nested class.
  • Nested class cũng có thể khai báo private, public, protected, default.

Syntax

class OuterClass {
   ...
   class NestedClass {
        ... 
   }
}

Một nested class được xem như là một thuộc tính của class chứa nó và có thể khai báo với các access modifier  private, public, protected,… 

public class OuterClass {
    //....
    private class PrivateInnerClass {
        // ... 
    }
    
    public class PublicInnerClass{
        // ...
    }
}

Các loại Nested class trong java

Nested class trong java được chia thành 2 loại:

  • Static
  • Non-static

Ví dụ

public class OuterClass {
    static class StaticNestedClass{
        // ...
    }

    class InnerClass{
        // ...
    }
}

Static Nested class

Static nested class cũng giống như các biến, method static của class, static nested class không thể tham chiếu trực tiếp đến biến hoặc các method được khai báo trong nó. Chúng ta chỉ có thể sử dụng chúng thông qua tham chiếu đối tượng

Truy cập static nested class thông qua tên của class chứa nó

OuterClass.StaticNestedClass

Khởi tạo nested class:

OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();

Ví dụ

class OuterClass {
    // static member 
    static int outer_x = 10;

    // instance(non-static) member 
    int outer_y = 20;

    // private member 
    private static int outer_private = 30;

    // static nested class 
    static class StaticNestedClass {
        void display() {
            // Truy cap thanh vien static cua outer class
            System.out.println("outer_x = " + outer_x);
            // Truy cap thanh vien private cua outer class
            System.out.println("outer_private = " + outer_private);
        }
    }
}

public class StaticNestedClassDemo {
    public static void main(String[] args) {
        // Khoi tao static nested class
        OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

        nestedObject.display();

    }
}

Output:

outer_x = 10
outer_private = 30

Inner class

Một instance của Inner class chỉ có thể tồn tại với một instance của Outer class. và một đặc điểm quan trọng là bạn sẽ không thể bất kỳ một biến hay method… static trong inner class. để khởi tạo một Inner class:

OuterClass outerClass = new OuterClass();
OuterClass.InnerClass innerClass = outerClass.new InnerClass();

Ví dụ: 

Class Student chứa các thông tin name, address, sex, score. Student có một Inner class StudentOperator sẽ đảm nhiệm những chức năng mà Student cần, ở đây mình demo 2 method chính là print()type().

public class Student {
    private String name;
    private String address;
    private String sex;
    private int score;

    public Student(String name, String address, String sex, int score) {
        this.name = name;
        this.address = address;
        this.sex = sex;
        this.score = score;
    }

    class StudentOperator {
        public void print() {
                System.out.print(name + " -  " + address + " -  " + sex + " - " + score + ": ");
        }

        public void type() {
            if(score <5) {
                System.out.println("Hoc luc yeu");
            } else if (score >= 5 && score <= 8) {
                System.out.println("Hoc luc kha");
            }
            else {
                System.out.println("Hoc luc gioi");
            }

        }
    }

    public void typefStudent() {
        Student.StudentOperator studentOperator = this.new StudentOperator();
        studentOperator.print();
        studentOperator.type();
    }
}
public class Main {

    public static void main(String[] args) {
	    Student student = new Student("HAI", "DONG NAI", "MALE", 10);
	    student.typefStudent();
    }
}
Output: HAI – DONG NAI – MALE – 10: Hoc luc gioi

 

Hàm typefStudent() của Student chỉ đơn giản khởi tạo StudentOperator và  gọi 2 hàm print()type() của nó. Chúng ta sẽ có output như trên. 

Note:

ở đây chúng ta thấy StudentOperator là class chỉ thực hiện các chức năng theo mong muốn của Student, vì vậy nên chỉ được sử dụng cho Student nên chúng ta có thể đưa nó vào là một Inner class cho Student.

Chúng ta có 2 loại khác của inner class là Local class được khai báo bên trong một block hoặc Anonymous class cũng được khai báo bên trong block nhưng chúng không có tên.

Nguồn tham khảo

https://www.geeksforgeeks.org/nested-classes-java/

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x