Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!"); 
    }

    }  
like image 359
brain storm Avatar asked Mar 10 '14 18:03

brain storm


Video Answer


1 Answers

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.

like image 144
rgettman Avatar answered Oct 01 '22 21:10

rgettman