Reputation: 151
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.
Upvotes: 14
Views: 52000
Reputation: 7899
No , Overriding means inherit the behavior from parent class and that is not possible without extending the class.
public class PClass
{
protected boolean methodA()
{
return true;
}
}
public class CClass extends PClass
{
protected boolean methodA()
{
return false;
}
}
Run the code below to test it
public static void main(String[] args)
{
PClass pc = new CClass();
System.out.println(pc.methodA());
}
O/p=false
here we are overriding the behavior of methodA
Upvotes: 2
Reputation: 12751
You can only override methods through extension.
You can override a protected method with an anonymous subclass, if you like. E.g.
public class Animal {
protected String getSound() {
return "(Silence)";
}
public void speak() {
System.out.println(getSound());
}
}
In another class:
public static void main(String ... args) {
Animal dog = new Animal() {
@Override
protected String getSound() {
return "Woof!";
}
}
dog.speak();
}
Will output:
Woof!
Upvotes: 10
Reputation: 14363
Overriding by definition says..
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
So AFAIK if you don't extend the super class there is no way to override the method.
Upvotes: 0
Reputation: 7957
In order to override a method you have to extend that class. That's what overriding means: having a method with the same signature as the super-class.
Upvotes: 0
Reputation: 23186
Upvotes: 37