Here are a couple of Java inheritance tests that you might run into during a Java programming job interview.
This first test is a good test to see if Java developers understand how inheritance works. Just read the following code, and then answer the question, “What do you think it will print?”
public class InheritanceTest { public static void main(String[] args) { Parent c = new Child(); c.doSomething(); } } class Parent { public void doSomething() { System.err.println("Parent called"); } } class Child extends Parent { public void doSomething() { System.err.println("Child called"); } }
Lots of people seem to guess that it will print:
Parent called Child called
but if you thought that, surprise, it doesn’t. In the case of a child method like this, it doesn’t automatically call a parent method, even if the parent method has the same name and signature.
If that’s the behavior you want, your child method needs to explicitly call the parent method, like this:
class Child extends Parent { public void doSomething() { super.doSomething(); System.err.println("Child called"); } }
After you’ve changed your child method to look like this, when you run this little program you’ll then get this output:
Parent called Child called
An interesting followup
An interesting followup question is what happens when, instead of talking about methods, we look at how the constructors are called? For instance, what’s printed out in the following example?
public class InheritanceTest { public static void main(String[] args) { Parent c = new Child(); } } class Parent { public Parent() { System.err.println("Parent called"); } } class Child extends Parent { public Child() { System.err.println("Child called"); } }
In the case of constructors, the parent method is called automatically, so the output is:
Parent called Child called
As you can see, inheritance is different for (a) Java constructors and (b) Java methods.