Access modifiers and superclass reference methods

Why is it that when I create a superclass link in subclasses, you can call only methods that are publicly available from the link, and not protected methods. (Classes are in different packages)

package pet;

public class Dog {
    protected void bark(){};
    void jump(){};  
    public void lick(){};
}


package other;
import pet.*;

public class Husky extends Dog {
    public static void main(String[] args){ 
        Husky h = new Husky();
        h.bark();     //COMPILES (Husky is a subclass of Dog - Protected method)
        h.jump();     //DOES NOT COMPILE (Different packages - package-private access method)

        Dog d = new Dog();
        d.bark();   //DOES NOT COMPILE WHY?
        d.jump();   //DOES NOT COMPILE (Different packages - package-private access method)
        d.lick();   //COMPILES (Method is public)
    }
}

My question is why d.bark () is not compiling ? The cortex method has a protected access modifier that allows it to access classes from one package or subclasses. So what is going on?

If a hoarse link can access the bark method, by the same logic, the link to the dog should also have access to the bark method.

So, I can only assume that the problem with the Dog link should be the problem?

+4
1

, . @vikss , Super , , Huskey . :

Dog d = new Dog();
    d.bark(); 

, . Dog Dog. , .

d.bark(); , Huskey. , Dog d = new Dog(); d.bark(); - Huskey ( ), bark() - ( ).

, !

0

Source: https://habr.com/ru/post/1607705/


All Articles