I'm new to Java and I have a very basic question.
I have 2 Parent Class under the same package. Animal
Abstract Class and the Machine
Class.
Now, the Animal
Abstract Class has a protected method. I'm aware that protected methods are accessible if the classes are under the same package.
I can access that protected method in my Machine
Class, and the question is.. Is it possible to override that protected method? Without extending the Animal
Class.
The method with protected access modifier can be marked with virtual keyword in a base class, because the protected members of a class are inherited through inheritance, so they can be overridden in its derived class.
protected means access to the method is restricted to the same package or by inheritance. So the answer is, yes, protected methods can be overridden by a subclass in any package. By contrast, package (default) scoped methods are not visible even to subclasses that are in a different package.
A protected method is like a private method in that it can only be invoked from within the implementation of a class or its subclasses. It differs from a private method in that it may be explicitly invoked on any instance of the class, and it is not restricted to implicit invocation on self .
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs. If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With