The below has this output.
Hello World!
main.ConstructedDerivedClass:6.0
main.ConstructedDerivedClass:6.0
public class ConstructedDerivedClass extends ConstructedBase {
private static final double version = 6.0;
public static void main(String[] args) {
System.out.println("Hello World!");
ConstructedDerivedClass derivedClass = new ConstructedDerivedClass();
}
public ConstructedDerivedClass() {
showMyAttributes();
}
@Override
protected void showMyAttributes() {
System.out.println(this.getClass().getName() + ":" + version);
}
}
public class ConstructedBase {
private static final double version = 15.0;
public ConstructedBase() {
showMyAttributes();
}
protected void showMyAttributes() {
System.out.println(this.getClass().getName() + ":" + version);
}
}
I would expect it to just display one line, that of the child class (ConstructedDerivedClass). But instead it print's out twice.I know in general you should avoid calling overriden methods from a constructor, but I wanted to see for myself how was this working.
Actually, I get why version is '6.0' on both lines - since field is being declared static of course static fields are initialized first. But still don't get why two lines.
Any guidance would be appreciated.
In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes.
When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the way by which java achieve Run Time Polymorphism.
Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
You cannot change the method signature when overriding methods (except narrowing the return type and exceptions). You can of course overload the method multiple times (and override those), but the superclass needs to know all combinations.
This is because when you write
public ConstructedDerivedClass() {
showMyAttributes();
}
The compiler actually places a call to super default constructor in byte code so it's equivalent to
public ConstructedDerivedClass() {
super();
showMyAttributes();
}
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