Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Protected Methods

Tags:

java

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.

like image 508
Dennis Salibio Avatar asked Jul 24 '12 07:07

Dennis Salibio


People also ask

Can we override protected method in C#?

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.

Can protected method be inherited?

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.

What is a protected method?

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 .

Do overridden methods need to be public?

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.


1 Answers

  • protected - Can be overridden by subclasses, whether they are in the same package or not
  • default (no access modifier) - can only be accessed or overridden if both the classes are in the same package
like image 119
Jeshurun Avatar answered Sep 19 '22 04:09

Jeshurun