Search code examples
javainheritancemethodsconstructoraccess-modifiers

Java inheritance: Reducing visibility in a constructor vs inherited method


In the following code, the constructor of Child has reduced visibility from public to private, which is allowed. The inherited methods, such as test(), cannot have reduced visibility. Why does Java operate this way?

class Parent { 
        public Parent(){}

       public void test()  
        {  
            System.out.print("parent test executed!");  
        }
}

class Child extends Parent{  

    private Child(){}

    private void test(){
        System.out.print("child test executed!"); 
    }

    }  

Solution

  • Constructors are not inherited, so Child() doesn't override Parent().

    As for the methods, if you have (if Child() were public)

    Parent p = new Child();
    p.test();
    

    Had it been allowed, this would be invoking a private method. So narrowing the access while overriding is not permitted.