Java Gotchas

Overloading Gotcha

Let’s consider couple of java classes

public class AirCraft {

}
public class C141AirCraft extends AirCraft {

}
public class Pilot {

    public void flyAirCraft(AirCraft airCraft) {
       System.out.println("Flying Plain Air Craft");
   }
}
public class C141Pilot extends Pilot {

    @Override
    public void flyAirCraft(AirCraft airCraft) {
      System.out.println("C141Pilot Flying Plain Air Craft");
    }

    public void flyAirCraft(C141AirCraft c141AirCraft) {
      System.out.println("C141Pilot Flying C141 Air Craft");
   }
}

What the following code would print out ?

Pilot c141Pilot = new C141Pilot();
c141Pilot.flyAirCraft(new C141AirCraft());

If you say C141Pilot Flying C141 Air Craft ? then that’s not the correct answer.

It prints the following
C141Pilot Flying Plain Air Craft

Why? As per the Java Language Specification Section 8.4.9 The signature of the method to invoked is determined at compile time, However actual method invocation on the target instance happens at run time using dynamic method lookup.

Field Shadowing Gotcha

Let’s consider couple of java classes

public class Parent {
    public String name = "Parent";
}
public class Child extends Parent {
	public String name = "Child";
}

What the following code would print out ?

Parent parent = new Child();
Child child = new Child();
System.out.println(parent.name);
System.out.println(child.name);

If you think the two output statements would print
Child
Child

Then your assumption is in correct.

As per this Java tutorial, Java data members are not Polymorphic. Parent.name and Child.name are two distinct variables, that happen to have the same name.

The output would be

Parent
Child

A Subclass variable shadows the super class variable, However then both can be accessed individually.