> Java > java지도 시간 > 본문

Java의 보호된 키워드

WBOY
풀어 주다: 2024-08-30 15:22:35
원래의
235명이 탐색했습니다.

보호된 키워드는 변수, 메서드, 생성자에 액세스할 수 있는 범위를 제한하는 데 사용되는 키워드입니다. Java의 액세스 수정자 유형 중 하나입니다. 이는 메소드, 변수, 생성자 및 클래스의 범위를 구별하는 데 사용됩니다. Java에는 4가지 유형의 액세스 수정자가 있으며 다음과 같습니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사
  1. 기본 키워드: 패키지 내부에서만 접근할 수 있고 외부에서는 호출할 수 없습니다. 이름에서 알 수 있듯이 액세스 지정자가 언급되지 않으면 자동으로 기본값으로 할당됩니다.
  2. 공개 키워드: 프로그램 어디에서나 액세스할 수 있습니다. 이는 동일하거나 다른 클래스, 동일하거나 다른 패키지에서 사용할 수 있음을 의미합니다.
  3. 비공개 키워드: 클래스 외부 어디에서도 키워드에 액세스할 수 없도록 하여 키워드를 더 높은 수준으로 제한합니다.
  4. 보호 키워드: 이 글에서는 보호 키워드에 대해 자세히 알아 보겠습니다.

변수나 메소드가 보호됨으로 표시되면 아래 메소드를 통해서만 액세스할 수 있습니다.

  • 선언된 클래스와 동일한 클래스 내부
  • 선언된 클래스와 동일한 패키지에 있는 다른 클래스에서.
  • 패키지에 관계없이 선언된 클래스에서 상속되는 클래스입니다.

보호 키워드는 클래스 외부의 변수에 액세스하기 위해 도입되었으며(비공개 키워드의 경우 불가능) 특정 메소드만 동일한 것을 상속할 수 있다는 점에서 공개 키워드와 비공개 키워드의 조합과 같습니다.

구문

보호된 키워드는 앞에 '보호됨'이라는 키워드가 붙어 선언됩니다. 먼저 아래와 같이 “MyClass”라는 클래스 중 하나에서 보호 키워드를 선언합니다.

class MyClass {
protected String name = "Katy";
protected int token= 55;
}
public class SubClass extends MyClass {
public static void main(String[] args) {
SubClass obj = new SubClass();
System.out.println(obj.name + "'s token number is: " + obj.token);
}
}
로그인 후 복사

여기서 "SubClass" 클래스는 "MyClass"를 확장하므로 여기서는 SubClass의 객체를 생성하고 변수를 호출하여 protected 키워드를 사용할 수 있습니다.

출력:

 Java의 보호된 키워드

보호된 키워드는 멤버 수준, 즉 함수 외부에 선언되고 정적이 아닌 내부 클래스에서만 사용할 수 있습니다. Protected 키워드는 클래스 외부 및 다른 패키지의 하위 클래스에서 액세스할 수 있다는 점에서 private 키워드와 다릅니다.

보호된 키워드 사용에 대한 몇 가지 제한 사항은 다음과 같습니다.

  • 클래스를 보호됨으로 선언하는 데 사용할 수 없습니다.
  • 인터페이스는 보호됨으로 선언할 수 없습니다.
  • 패키지 외부의 접근성은 상속을 통해서만 가능합니다.
  • 보호된 생성자는 해당 인스턴스를 생성하여 패키지 외부에서 액세스할 수 없습니다.

Java의 보호키워드 예시

보호 키워드의 개념을 더 잘 이해할 수 있는 몇 가지 예를 살펴보겠습니다.

1. 상위 클래스를 확장하지 않고 보호된 키워드 호출

여기에서는 "package1"의 상위 클래스에서 키워드를 호출하려고 합니다. "package2"에는 "ProtectedExample2"가 생성되어 있고 여기서는 "disp"라는 키워드가 호출됩니다. 그러나 하위 클래스가 기본 클래스에서 해당 값을 상속받지 않았으므로 코드는 키워드에 액세스할 수 없으며 표시된 대로 예외가 발생합니다.

코드:

package com.package1;
public class Example {
protected String disp="Printing message from protected variable from package1";
}
//Create new package as com.package2
//Create new class as ProtectedExample2
package com.package2;
import com.package1.Example;
public class ProtectedExample2 {
public static void main(String[] args) {
ProtectedExample2 a=new ProtectedExample2();
System.out.println(a.disp);
}
}
로그인 후 복사

출력:

Java의 보호된 키워드

2. 보호 클래스에 액세스

이 예에서는 보호된 클래스 “ProtectedExample5”에 액세스하려고 합니다. 이로 인해 컴파일 오류가 발생합니다.

코드:

protected class ProtectedExample5 {
void display()
{
System.out.println("Try to access outer protected class");
}
public static void main(String[] args) {
ProtectedExample5 p=new ProtectedExample5();
p.display();
}
}
로그인 후 복사

출력:

Java의 보호된 키워드

3. 동일한 패키지이지만 다른 클래스의 보호된 키워드 표시

아래 예에서는 먼저 "com.package1"이라는 패키지를 만들고 "Example"이라는 이름으로 새 클래스를 만듭니다. 여기서는 키워드 "disp"가 보호됨을 선언합니다. 우리는 "Example1" 클래스를 사용하여 이 보호된 키워드를 표시하려고 합니다. 이를 위해서는 먼저 상위 클래스 “Example1”의 객체를 생성한 후 키워드 “disp”에 할당된 값을 출력해야 합니다.

코드:

package com.package1;
public class Example {
protected String disp="Printing message from protected variable from package1";
}
class Example1 {
public static void main(String[] args) {
Example obj=new Example();
System.out.println(obj.disp);
}
}
로그인 후 복사

출력:

Java의 보호된 키워드

4. Displaying protected keyword from a different package

Using the same code as above, we shall see how to call the protected keyword by creating a different package, “package2”. A protected keyword can be accessed only through inheritance from package1; hence “ProtectedExample2” is extended from “Example”. In a similar way as the first example, we have to create an object of the class “ProtectedExample2” in order to access the protected keyword from package “com.package1”.

Code:

package com.package2;
import com.package1.Example;
public class ProtectedExample2 extends Example{
public static void main(String[] args) {
ProtectedExample2 a=new ProtectedExample2();
System.out.println(a.disp);
}
}
로그인 후 복사

Output:

Java의 보호된 키워드

5. Accessing a protected class by overriding to sub-class

Here the class is declared as protected inside the inherited class “Example5”. Also, a protected class called “Example” is declared outside the function but in the same package. When an object of “Example5” is created and the protected class “disp()” is called, we can observe that the overridden method is called instead of the outside class. This is because we shall not be able to import “com.package1” and its class “Example” since it is not visible and causes a compilation error.

Code:

//Create a file by Example.java
package com.package1;
class Example
{
protected void disp()
{
System.out.println("Printing from protected class in the outside function");
}
}
//Create a class by the name Example5.java
public class Example5 extends Example {
protected void disp()
{
System.out.println("Accessing the overriden function");
}
public static void main(String[] args) {
Example5 exp=new Example5();
exp.disp();
}
}
로그인 후 복사

Output:

Java의 보호된 키워드

Importance of Protected Keyword

The importance of protected keyword in java is:

  • These keywords allow the classes or their variables to be inherited from their parent class which is not possible with any other restricted keyword such as private.
  • A protected keyword is the combination of a private keyword’s advantage and that of a public keyword. It eliminates the disadvantage of public keyword that the variable or class be accessible from anywhere in the program by restricting the scope.

Conclusion

As shown in the above examples, we choose protected keywords depending on the access level we require at the code level. They help greatly in cases where the same variable or class needs to be accessed from other inherited methods in the program. A parent-child relationship is always present between the parent class and its sub-classes which are using the protected keyword.

위 내용은 Java의 보호된 키워드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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