Default access modifier for a Java constructor

前端 未结 4 610
悲哀的现实
悲哀的现实 2020-12-01 06:25

Can anybody explain what the default access modifier is for an explicit no-arg constructor (and other constructors)?

4条回答
  •  粉色の甜心
    2020-12-01 06:56

    - A constructor will have a access-control of type default when no access-modifier is defined explicitly. So this constructor will have a Package Level Access. Classes which are defined within that package as that of the class with this default constructor will be able to access it and also the classes that extend this class containing the default constructor will be able to access it via inheritance.

    - If the constructor is made private, then only the code within that class can access this.

    Singleton example

    public class Test {
    
      private static Test uniqueInstance = new Test();
    
      private Test(){}
    
      public static Test getInstance(){
    
        return uniqueInstance;
    
     }
    
    
    }
    

    - Even non-static inner classes with in the class has access to its Private memebers and vice-versa.

    Eg:

    public class T {
    
    
        private T(){
    
            System.out.println("Hello");
        }
    
        class TT{
    
            public TT(){
    
                new T();
            }
        }
    
        public static void main(String[] args){
    
            T t = new T();
            T.TT i = t.new TT();
    
        }
    
    }
    

提交回复
热议问题