산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

Java 중첩 및 내부 클래스

자바 중첩 및 내부 클래스

이 튜토리얼에서는 예제를 통해 Java의 중첩 클래스와 해당 유형에 대해 알아봅니다.

자바에서는 다른 클래스 내에서 클래스를 정의할 수 있습니다. 이러한 클래스를 nested class라고 합니다. . 예를 들어,

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

Java에서 생성할 수 있는 중첩 클래스에는 두 가지 유형이 있습니다.

권장 도서 :

먼저 비정적 중첩 클래스를 살펴보겠습니다.

<시간>

비정적 중첩 클래스(내부 클래스)

비정적 중첩 클래스는 다른 클래스 내의 클래스입니다. 바깥쪽 클래스(외부 클래스)의 멤버에 액세스할 수 있습니다. 일반적으로 inner class으로 알려져 있습니다. .

inner class 이후 외부 클래스 내에 존재하는 경우 내부 클래스를 인스턴스화하려면 먼저 외부 클래스를 인스턴스화해야 합니다.

다음은 Java에서 내부 클래스를 선언하는 방법의 예입니다.

예시 1:내부 클래스

class CPU {
    double price;
    // nested class
    class Processor{

        // members of nested class
        double cores;
        String manufacturer;

        double getCache(){
            return 4.3;
        }
    }

    // nested protected class
    protected class RAM{

        // members of protected nested class
        double memory;
        String manufacturer;

        double getClockSpeed(){
            return 5.5;
        }
    }
}

public class Main {
    public static void main(String[] args) {

        // create object of Outer class CPU
        CPU cpu = new CPU();

       // create an object of inner class Processor using outer class
        CPU.Processor processor = cpu.new Processor();

        // create an object of inner class RAM using outer class CPU
        CPU.RAM ram = cpu.new RAM();
        System.out.println("Processor Cache = " + processor.getCache());
        System.out.println("Ram Clock speed = " + ram.getClockSpeed());
    }
}

출력 :

Processor Cache = 4.3
Ram Clock speed = 5.5

위의 프로그램에는 두 개의 중첩 클래스가 있습니다. ProcessorRAM 외부 클래스 내부:CPU . 내부 클래스를 protected로 선언할 수 있습니다. 따라서 RAM 클래스를 protected로 선언했습니다.

Main 클래스 내부

참고 :점(. ) 연산자를 사용하여 외부 클래스를 사용하여 내부 클래스의 인스턴스를 생성합니다.

<시간>

내부 클래스 내의 외부 클래스 멤버 액세스

이 키워드를 사용하여 외부 클래스의 멤버에 액세스할 수 있습니다. 이 키워드에 대해 알아보려면 Java this 키워드를 방문하십시오.

예시 2:회원 접근

class Car {
    String carName;
    String carType;

    // assign values using constructor
    public Car(String name, String type) {
        this.carName = name;
        this.carType = type;
    }

    // private method
    private String getCarName() {
        return this.carName;
    }

// inner class
    class Engine {
        String engineType;
        void setEngine() {

           // Accessing the carType property of Car
            if(Car.this.carType.equals("4WD")){

                // Invoking method getCarName() of Car
                if(Car.this.getCarName().equals("Crysler")) {
                    this.engineType = "Smaller";
                } else {
                    this.engineType = "Bigger";
                }

            }else{
                this.engineType = "Bigger";
            }
        }
        String getEngineType(){
            return this.engineType;
        }
    }
}

public class Main {
    public static void main(String[] args) {

// create an object of the outer class Car
        Car car1 = new Car("Mazda", "8WD");

        // create an object of inner class using the outer class
        Car.Engine engine = car1.new Engine();
        engine.setEngine();
        System.out.println("Engine Type for 8WD= " + engine.getEngineType());

        Car car2 = new Car("Crysler", "4WD");
        Car.Engine c2engine = car2.new Engine();
        c2engine.setEngine();
        System.out.println("Engine Type for 4WD = " + c2engine.getEngineType());
    }
}

출력 :

Engine Type for 8WD= Bigger
Engine Type for 4WD = Smaller

위의 프로그램에는 Engine이라는 내부 클래스가 있습니다. 외부 클래스 Car 내부 . 여기서 줄을 주목하세요.

if(Car.this.carType.equals("4WD")) {...}

this를 사용하고 있습니다. carType에 액세스하는 키워드 외부 클래스의 변수 this.carType을 사용하는 대신 Car.this.carType를 사용했습니다. .

외부 클래스 Car의 이름을 언급하지 않았기 때문입니다. , this 키워드는 내부 클래스 내부의 멤버를 나타냅니다.

마찬가지로 내부 클래스에서 외부 클래스의 메서드에 액세스하고 있습니다.

if (Car.this.getCarName().equals("Crysler") {...}

getCarName() private입니다. 메서드를 사용하면 내부 클래스에서 액세스할 수 있습니다.

<시간>

정적 중첩 클래스

Java에서는 static도 정의할 수 있습니다. 다른 클래스 안의 클래스. 이러한 클래스를 static nested class이라고 합니다. . 정적 중첩 클래스는 정적 내부 클래스라고 하지 않습니다.

내부 클래스와 달리 정적 중첩 클래스는 외부 클래스의 멤버 변수에 액세스할 수 없습니다. 정적 중첩 클래스 때문입니다. 외부 클래스의 인스턴스를 만들 필요가 없습니다.

OuterClass.NestedClass obj = new OuterClass.NestedClass();

여기에서 정적 중첩 클래스의 개체를 만들고 있습니다. 단순히 외부 클래스의 클래스 이름을 사용하여. 따라서 OuterClass.this를 사용하여 외부 클래스를 참조할 수 없습니다. .

예시 3:정적 내부 클래스

class MotherBoard {

   // static nested class
   static class USB{
       int usb2 = 2;
       int usb3 = 1;
       int getTotalPorts(){
           return usb2 + usb3;
       }
   }

}
public class Main {
   public static void main(String[] args) {

       // create an object of the static nested class
       // using the name of the outer class
       MotherBoard.USB usb = new MotherBoard.USB();
       System.out.println("Total Ports = " + usb.getTotalPorts());
   }
}

출력 :

Total Ports = 3

위의 프로그램에서 USB라는 정적 클래스를 만들었습니다. 마더보드 클래스 내부 . 줄을 주목하십시오.

MotherBoard.USB usb = new MotherBoard.USB();

여기에서 USB 객체를 생성합니다. 외부 클래스의 이름을 사용합니다.

이제 외부 클래스의 멤버에 액세스하려고 하면 어떻게 되는지 살펴보겠습니다.

<시간>

예제 4:정적 내부 클래스 내부의 외부 클래스 멤버 접근

class MotherBoard {
   String model;
   public MotherBoard(String model) {
       this.model = model;
   }

   // static nested class
   static class USB{
       int usb2 = 2;
       int usb3 = 1;
       int getTotalPorts(){
           // accessing the variable model of the outer classs
           if(MotherBoard.this.model.equals("MSI")) {
               return 4;
           }
           else {
               return usb2 + usb3;
           }
       }
   }
}
public class Main {
   public static void main(String[] args) {

       // create an object of the static nested class
       MotherBoard.USB usb = new MotherBoard.USB();
       System.out.println("Total Ports = " + usb.getTotalPorts());
   }
}

프로그램을 실행하려고 하면 오류가 발생합니다.

error: non-static variable this cannot be referenced from a static context

외부 클래스의 객체를 사용하여 내부 클래스의 객체를 생성하지 않기 때문입니다. 따라서 외부 클래스 Motherboard에 대한 참조가 없습니다. Motherboard.this에 저장됨 .

<시간>

기억해야 할 핵심 사항


java

  1. C# 중첩 클래스
  2. 자바 변수와 리터럴
  3. 자바 클래스와 객체
  4. 자바 최종 키워드
  5. 자바 instanceof 연산자
  6. 자바 추상 ​​클래스와 추상 메소드
  7. 자바 중첩 정적 클래스
  8. 자바 익명 클래스
  9. 자바 싱글톤 클래스
  10. 자바 리플렉션