Reputation: 116
I have a class A that extends a class B.
A is defined like this, it also overrides a method of B:
class A extends B
{
public A() {
super();
}
@Override
public void doSomething(){
//does something
}
}
B is defined like this:
public class B
{
public B(){
doSomething();
}
public void doSomething(){
//does something
}
}
So if I initialize an object of A, the constructor calls the one of the superclass that calls the method doSomething()
. But which one will be executed? B's implementation or the overriden one in A?
Upvotes: 0
Views: 144
Reputation: 120848
That is a common bug, only call final
methods in constructor, the method from A
will be called.
Btw Sonar
(if you have it) will trigger a rule here saying that you should not call polymorphic methods inside a constructor.
Upvotes: 3
Reputation: 1057
If the class Overrides a method, then the overriden method will be called. Try the example below:
public class A {
void doSomething() {
System.out.println("a");
}
}
public class B extends A {
@Override
void doSomething() {
System.out.println("b");
}
}
A a = new B();
a.doSomething(); // will print "b"
Upvotes: 0