Constructors and Inheritance in Java
Hi there,
I'm going over access modifiers in Java from this website and noticed that the following output is displayed if you run the snippet of code.
Cookie Class
Code :
import javax.swing.*;
public class Cookie {
public Cookie() {
System.out.println("Cookie constructor");
}
protected void foo() {
System.out.println("foo");
}
}
ChocolateChip class
Code :
public class ChocolateChip extends Cookie {
public ChocolateChip() {
System.out.println("ChocolateChip constructor");
}
public static void main(String[] args) {
ChocolateChip x = new ChocolateChip();
x.foo();
}
}
Output:
Code :
Cookie constructor
ChocolateChip constructor
foo
I've been told that constructors are never inherited in Java, so why is "Cookie constructor" still in the output? I know that ChocolateChip extends Cookie, but the Cookie constructor isn't enacted when the new ChocolateChip object is defined... or is it?
If you can shed any light on this, I would greatly appreciate it.
Many thanks!
Re: Constructors and Inheritance in Java
You are correct that constructors are not inherited. However, each constructor calls the super constructor all the way upto Object class (which doesn't call super as it is the top level class). If you do not insert a call to the super class constructor then the compiler will insert one implicitly. Therefore the constructor in the ChoclateChip class is actually:
Code java:
public ChocolateChip() {
super();
System.out.println("ChocolateChip constructor");
}
Re: Constructors and Inheritance in Java
One more thing to note, due to this many people make the following mistake and wonder why their code will not compile.
Code java:
public class Cookie {
public Cookie(String s) {
System.out.println("Cookie constructor");
}
protected void foo() {
System.out.println("foo");
}
}
public class ChocolateChip extends Cookie {
public ChocolateChip() {
System.out.println("ChocolateChip constructor");
}
}
The error is caused by the child class trying to call the default no arg constructor in the parent class but it does not exist.
Re: Constructors and Inheritance in Java
Quote:
Originally Posted by
Junky
You are correct that constructors are not inherited. However, each constructor calls the super constructor all the way upto Object class (which doesn't call super as it is the top level class). If you do not insert a call to the super class constructor then the compiler will insert one implicitly. Therefore the constructor in the ChoclateChip class is actually:
Code java:
public ChocolateChip() {
super();
System.out.println("ChocolateChip constructor");
}
Hi Junky,
I didn't realize that the compiler can insert super() implicitly.
Many thanks for your clarification and quick reply!