> Java > java지도 시간 > Java의 중첩 클래스

Java의 중첩 클래스

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
풀어 주다: 2024-08-30 16:00:19
원래의
811명이 탐색했습니다.

중첩 클래스는 다른 클래스 내부에 있는 클래스를 의미합니다. Java를 사용하면 Java에서 중첩 클래스를 만들 수 있습니다. 중첩 클래스는 외부 클래스의 멤버 중 하나입니다. 공개, 비공개, 보호 또는 기본값으로 선언할 수도 있습니다. 중첩 클래스는 외부 클래스의 다른 멤버에 액세스할 수 있지만 그 반대의 경우는 불가능합니다. 이는 중첩 클래스가 자신을 둘러싸는 외부 클래스의 멤버이므로 외부 클래스가 중첩 클래스 멤버에 액세스할 수 없음을 의미합니다. 따라서 점(.)을 사용하여 중첩 클래스 및 해당 멤버에 액세스합니다. 중첩 클래스에는 정적 키워드가 없습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java의 중첩 클래스 범주

중첩 클래스는 두 가지 범주로 나뉩니다.

  1. 정적 중첩 클래스: "정적"이라는 키워드로 선언된 중첩 클래스를 정적 ​​중첩 클래스라고 합니다. 정적 중첩 클래스는 외부 클래스를 참조하여 액세스할 수 있습니다. 정적 클래스가 있는 중첩 클래스는 외부 클래스의 비정적 변수 및 메서드에 액세스할 수 없습니다.
  2. 내부 클래스: 비정적 중첩 클래스는 정적으로 선언되지 않은 내부 클래스입니다. 비공개로 선언된 경우에도 정적 중첩 클래스는 모든 정적 및 비정적 변수 및 메서드에 액세스할 수 없습니다. 내부 클래스도 2가지 종류가 있습니다.
  • 로컬 내부 클래스
  • 익명 내부 클래스

구문:

아래 구문에서 OuterClass에는 Nested 클래스로 알려진 InnerClass 내부 클래스가 있습니다.

1

2

3

4

5

6

7

//Outer class

class OuterClass {

//Inner class as a nested class

class InnerClass {

....

}

}

로그인 후 복사

Java에서 중첩 클래스 사용

프로그래밍 세계에서 Nested 클래스는 아래와 같이 중요한 역할을 합니다.

  • 클래스 중첩은 다른 클래스 범위의 클래스를 그룹화하는 것과 같습니다. 다른 곳에서는 중첩 클래스를 사용할 수 없습니다.
  • 가독성 및 유지 관리 용이성: 클래스 중첩은 코드 가독성을 높이고 다른 클래스에 영향을 주지 않으므로 유지 관리가 더 쉽습니다.
  • 코드 감소: 중첩 클래스를 사용하면 코드 줄이 줄어들어 최적화가 가능합니다.
  • 캡슐화 증가: 중첩 클래스에서 내부 클래스는 바깥쪽 클래스의 멤버에 액세스할 수 있습니다. 동시에 외부 클래스는 내부 클래스 멤버에 직접 액세스할 수 없습니다. 또한 내부 클래스는 외부 프로그램에서 표시되거나 액세스할 수 없습니다.

Java의 중첩 클래스 예

아래는 Java의 중첩 클래스 예입니다.

예시 #1

이 예에서는 외부 클래스를 참조하여 내부 클래스의 인스턴스화를 관찰할 수 있습니다.

코드:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// Outer class which contains nested class

class Engine{

static double fuel = 20.0;

//static nested class

static class Ignition{

void showFuelSpend() {

System.out.println("Fuel Spend = " + fuel + " Ltrs");

}

}

}

//class uses nested class inside it

public class NestedClassExample{

public static void main(String[] args) {

//creating object of the nested class by referencing parent class

Engine.Ignition engIgnitObj = new Engine.Ignition();

//calling method of the nested class

engIgnitObj.showFuelSpend();

}

<u>}</u>

로그인 후 복사

출력:

Java의 중첩 클래스

예시 #2

이 예에서는 내부 클래스를 인스턴스화하는 방법을 볼 수 있습니다. 내부 클래스의 인스턴스를 생성하려면 내부 클래스의 인스턴스가 필요합니다. Outer 클래스의 인스턴스를 생성한 후 그 안에 중첩 클래스의 인스턴스를 생성하는 것이 가능해집니다.

코드:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

//Outer class

class Volume{

double x, y, z;

Volume(double x, double y, double z) {

this.x = x;

this.y = y;

this.z = z;

}

// Nested inner class

class Measurement{

//method to calculate the total area

void totalArea(double i, double j) {

System.out.println("\nArea for the provided container is " + (i * j));

}

//method to calculate the total volume

void totalVolume(double i, double j, double k) {

System.out.println("\nVolume for the provided container is " + (i * j * k));

}

}

}

public class NestedClassCalcExample {

public static void main(String[] args) {

//passing here all the parameter to constructor

Volume volObj = new Volume(30.0, 25, 18.0);

Volume.Measurement volMeasureObj = volObj.new Measurement();

// calculating total area

volMeasureObj.totalArea(volObj.x, volObj.y);

// calculating total volume

volMeasureObj.totalVolume(volObj.x, volObj.y, volObj.z);

}

}

로그인 후 복사

출력:

Java의 중첩 클래스

예시 #3

이 예는 외부 클래스의 인스턴스 내에서 중첩 클래스 객체의 인스턴스화가 어떻게 발생하는지 보여줍니다.

코드:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

//outer class

class Electronic{

String circuitName,

String circuitType;

double circuitCost;

//constructor of outer class

Electronic(String name, String type, double cost) {

this.circuitName = name;

this.circuitType = type;

this.circuitCost = cost;

}

String getCircuitName() {

return this.circuitName;

}

//nested class

class Circuit{

String circuitType;

double circuitCost;

void setCircuitType() {

this.circuitType = "Transistor";

this.circuitCost = 430.0;

}

//get circuit type using this method

String getCircuitType(){

return this.circuitType;

}

//get circuit cost using this method

double getCircuitCost(){

return this.circuitCost;

}

}

}

public class Product{

public static void main(String[] args) {

Electronic elObj = new Electronic("Amplifier", "Integrated", 375.0);

Electronic.Circuit circuit = elObj.new Circuit();

//printing here the values before reset it

System.out.println("\nCircuit Name : " + elObj.circuitName);

System.out.println("\nCircuit Type : " + elObj.circuitType);

System.out.println("\nCircuit Cost : " + elObj.circuitCost);

//resetting some value

circuit.setCircuitType();

//printing here the values before reset it

System.out.println("\n\nCircuit Name : " + elObj.getCircuitName());

System.out.println("\nCircuit Type : " + circuit.getCircuitType());

System.out.println("\nCircuit Cost : " + circuit.getCircuitCost());

}

}

로그인 후 복사

출력:

Java의 중첩 클래스

결론

위 기사에서는 Java에서 Nested 클래스가 어떻게 필수적인지 검토했습니다. 클래스 중첩을 활용하는 것이 좋습니다. 위 글에서는 Nested 클래스의 유용성에 대해서도 설명하고 있습니다.

위 내용은 Java의 중첩 클래스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿