Programing

기본 액세스 수정자는 무엇입니까?

lottogame 2020. 8. 14. 08:11
반응형

기본 액세스 수정자는 무엇입니까?


방금 Java 책을 읽기 시작했고 궁금했습니다. 지정되지 않은 경우 기본 액세스 수정자는 무엇입니까?


기본 가시성은 "개인 패키지"(명시 적으로 사용할 수는 없음)로 알려져 있습니다. 즉, 클래스가 속한 동일한 패키지 내에서 필드에 액세스 할 수 있습니다.

mdma가 지적했듯이, 기본값이 "공용"인 인터페이스 멤버에게는 사실이 아닙니다.

Java의 액세스 지정자 참조


기본 지정자는 컨텍스트에 따라 다릅니다.

클래스 및 인터페이스 선언의 경우 기본값은 패키지 전용입니다. 이는 보호 된 것과 개인용 사이에 속하며 동일한 패키지 액세스의 클래스 만 허용합니다. (protected는 이와 비슷하지만 패키지 외부의 하위 클래스에 대한 액세스도 허용합니다.)

class MyClass   // package private
{
   int field;    // package private field

   void calc() {  // package private method

   }
}

인터페이스 멤버 (필드 및 메서드)의 경우 기본 액세스는 공용입니다. 그러나 인터페이스 선언 자체의 기본값은 private 패키지입니다.

interface MyInterface  // package private
{
   int field1;         // static final public

   void method1();     // public abstract
}

그런 다음 선언이 있으면

public interface MyInterface2 extends MyInterface
{

}

MyInterface2를 사용하는 클래스는 MyInterface 자체의 선언을 볼 수 없더라도 공용이므로 super 인터페이스에서 field1 및 method1을 볼 수 있습니다.


액세스 지정자가 지정되지 않은 경우 클래스 및 클래스 멤버에 대한 패키지 수준 액세스 (이에 대한 명시 적 지정자가 없음)입니다. 인터페이스 메서드는 암시 적으로 공개됩니다.


기본 가시성 (NO 키워드)입니다 패키지 는 동일한 패키지에 위치하는 모든 클래스에 사용할 수 있다고하는 의미합니다.

흥미로운 점은 protected 가 하위 클래스뿐만 아니라 동일한 패키지의 다른 클래스에 대한 가시성을 제한하지 않는다는 것입니다.


그것이 무엇인지에 달려 있습니다.

  • 최상위 유형 (즉, 다른 유형 내에서 선언되지 않은 클래스, 열거 형, 인터페이스 및 주석 유형)은 기본적으로 패키지 전용 입니다. ( JLS §6.6.1 )

  • 클래스에서 모든 멤버 (필드, 메서드 및 중첩 된 형식 선언을 의미 함)와 생성자는 기본적으로 패키지 전용 입니다. ( JLS §6.6.1 )

    • 클래스에 명시 적으로 선언 된 생성자가 없으면 컴파일러 는 클래스와 동일한 액세스 지정자 를 가진 인수가없는 기본 생성자를 삽입합니다 . ( JLS §8.8.9 ) 기본 생성자는 일반적으로 항상 공개로 잘못 표시되지만 드물게는 동일하지 않습니다.
  • 열거 형에서 생성자는 기본적으로 비공개 입니다. 실제로 enum 생성자 private 이어야 하며 public 또는 protected로 지정하는 것은 오류입니다. 열거 형 상수는 항상 public 이며 액세스 지정자를 허용하지 않습니다. 열거 형의 다른 멤버는 기본적으로 패키지 전용 입니다. ( JLS §8.9 )

  • 인터페이스 및 주석 유형에서 모든 멤버 (다시 말하면 필드, 메서드 및 중첩 된 유형 선언을 의미 함)는 기본적으로 공용 입니다. 실제로 인터페이스 및 어노테이션 유형의 멤버는 공용 이어야 하며이를 개인 또는 보호로 지정하는 것은 오류입니다. ( JLS §9.3 ~ 9.5 )

  • 로컬 클래스는 메서드, 생성자 또는 이니셜 라이저 블록 내에 선언 된 명명 된 클래스입니다. 이들은 선언 된 .. 블록 으로 범위{}지정되며 액세스 지정자를 허용하지 않습니다. ( JLS §14.3 ) 리플렉션을 사용하면 다른 곳에서 로컬 클래스를 인스턴스화 할 수 있으며 해당 세부 사항이 JLS에 있는지 확실하지 않지만 package-private 입니다.

  • 익명 클래스는 new표현식에서 직접 클래스 본문을 지정하는 데 사용 되는 사용자 정의 클래스입니다 . ( JLS §15.9.5 ) 해당 구문은 액세스 지정자를 허용하지 않습니다. 리플렉션을 사용하면 다른 곳에서 익명 클래스를 인스턴스화 할 수 있으며 해당 세부 사항이 JLS에 있는지 확실하지 않지만 둘 다 및 생성 된 생성자는 package-private 입니다.

  • 인스턴스 및 정적 이니셜 라이저 블록에는 언어 수준 ( JLS §8.6 및 8.7 ) 에서 액세스 지정자가 없지만 정적 이니셜 라이저 블록은 이름이 지정된 메서드 <clinit>( JVMS §2.9 ) 로 구현 되므로 메서드에는 내부적으로 일부 액세스 지정자가 있어야합니다. 16 진 편집기를 사용하여 javac와 Eclipse의 컴파일러로 컴파일 된 클래스를 검사 한 결과 둘 다 package-private 로 메서드를 생성한다는 것을 발견했습니다 . 그러나 문자가 메서드 이름에서 유효하지 않고 리플렉션 메서드가 그 존재를 거부하도록 고정되어 <clinit>()있기 때문에 언어 내에서 호출 할 수 없으므로 효과적으로 액세스 지정자는 no access 입니다. 이 메서드는 클래스 초기화 중에 VM에서만 호출 할 수 있습니다.<>인스턴스 이니셜 라이저 블록은 별도의 메서드로 컴파일되지 않습니다. 코드가 각 생성자에 복사되므로 리플렉션을 통해서도 개별적으로 액세스 할 수 없습니다.


default 는 메소드 및 변수에 대한 액세스 수정 자로 사용되는 키워드입니다.
이 액세스 수정자를 사용하면 클래스, 변수, 메서드 또는 생성자가 자신의 클래스 또는 패키지에서 액세스 할 수있게되며 액세스 수정자가없는 경우에도 설정됩니다.

  Access Levels
    Modifier    Class   Package Subclass  EveryWhere
    public        Y        Y       Y         Y
    protected     Y        Y       Y         N
    default       Y        Y       N         N
    private       Y        N       N         N

인터페이스에서 기본값을 사용하면이 예제와 같은 메서드를 구현할 수 있습니다.

public interface Computer {    
    default void Start() {
        throw new UnsupportedOperationException("Error");
    }    
}

그러나 8 Java 버전에서만 작동합니다.

공식 문서

Java의 액세스 수정 자


See here for more details. The default is none of private/public/protected, but a completely different access specification. It's not widely used, and I prefer to be much more specific in my access definitions.


the default access specifier is package.Classes can access the members of other classes in the same package.but outside the package it appears as private


Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:

Bill Venners: Java has four access levels. The default is package. I have always wondered if making package access default was convenient because the three keywords that people from C++ already knew about were private, protected, and public. Or if you had some particular reason that you felt package access should be the default.

James Gosling: A package is generally a set of things that are kind of written together. So generically I could have done one of two things. One was force you always to put in a keyword that gives you the domain. Or I could have had a default value. And then the question is, what makes a sensible default? And I tend to go for what is the least dangerous thing.

So public would have been a really bad thing to make the default. Private would probably have been a bad thing to make a default, if only because people actually don't write private methods that often. And same thing with protected. And in looking at a bunch of code that I had, I decided that the most common thing that was reasonably safe was in the package. And C++ didn't have a keyword for that, because they didn't have a notion of packages.

But I liked it rather than the friends notion, because with friends you kind of have to enumerate who all of your friends are, and so if you add a new class to a package, then you generally end up having to go to all of the classes in that package and update their friends, which I had always found to be a complete pain in the butt.

But the friends list itself causes sort of a versioning problem. And so there was this notion of a friendly class. And the nice thing that I was making that the default -- I'll solve the problem so what should the keyword be?

For a while there actually was a friendly keyword. But because all the others start with "P," it was "phriendly" with a "PH." But that was only in there for maybe a day.

http://www.artima.com/intv/gosling2P.html


Update Java 8 usage of default keyword: As many others have noted The default visibility (no keyword)

the field will be accessible from inside the same package to which the class belongs.

Not to be confused with the new Java 8 feature (Default Methods) that allows an interface to provide an implementation when its labeled with the default keyword.

See: Access modifiers


There is an access modifier called "default" in JAVA, which allows direct instance creation of that entity only within that package.

Here is a useful link:

Java Access Modifiers/Specifiers


First of all let me say one thing there is no such term as "Access specifier" in java. We should call everything as "Modifiers". As we know that final, static, synchronised, volatile.... are called as modifiers, even Public, private, protected, default, abstract should also be called as modifiers . Default is such a modifiers where physical existence is not there but no modifiers is placed then it should be treated as default modifiers.

To justify this take one example:

public class Simple{  
    public static void main(String args[]){  
     System.out.println("Hello Java");  
    }  
}  

Output will be: Hello Java

Now change public to private and see what compiler error you get: It says "Modifier private is not allowed here" What conclusion is someone can be wrong or some tutorial can be wrong but compiler cannot be wrong. So we can say there is no term access specifier in java everything is modifiers.

참고URL : https://stackoverflow.com/questions/3530065/what-is-the-default-access-modifier

반응형