Inheritance, overriding and exceptions in Java
Which method runs at runtime, what static really means, and how try, catch and finally execute in order.
The second big area in Java screenings is how code behaves at runtime: which version of a method is called, what belongs to a class rather than an object, and the exact order in which exception blocks run.
Overriding is decided at runtime
When a subclass overrides a method, the version that runs depends on the actual object, not on the declared type of the variable. This is called dynamic dispatch.
class Animal { void sound() { System.out.println("..."); } }
class Dog extends Animal { void sound() { System.out.println("Woof"); } }
Animal a = new Dog();
a.sound(); // Woof
Overloading is different. Methods with the same name but different parameter lists are chosen at compile time from the argument types. Changing only the return type is not overloading; it is a compile error.
static belongs to the class
A static field has one copy shared by every object. A static method can be called without creating an object and cannot use this or instance fields directly. Static methods are not overridden; a subclass method with the same signature hides the parent version instead.
class Counter {
static int count = 0;
Counter() { count++; }
}
new Counter();
new Counter();
System.out.println(Counter.count); // 2
try, catch and finally
The finally block runs whether or not an exception is thrown, and even when the try block contains a return. The return value is worked out first, then finally runs, then the method returns.
static int test() {
try { return 1; }
finally { System.out.print("cleanup "); }
}
System.out.println(test()); // cleanup 1
Checked exceptions, such as IOException, must be caught or declared with throws. Unchecked exceptions extend RuntimeException, for example NullPointerException and ArithmeticException, and the compiler does not force you to handle them. Catch blocks must go from the most specific type to the most general, or the code will not compile.
Habit to build
For any snippet with inheritance, write down two things before answering: the declared type and the actual object type. The declared type decides what compiles; the actual type decides which overridden method runs.
More in Programming