Java – access modifiers and methods for superclass references [copy]
•
Java
See English answers > understanding Java's protected modifier 6
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) } }
Solution
Although access modifiers play an important role in inheritance, this issue should not be confused with inheritance As @vikss rightly said, super class doesn't know the following inheritance tree, so I don't know if huskey can access its protected members
Dog d = new Dog(); d.bark();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码