Monday, March 5, 2012

Overriding a method in inner class of parent class

Do you want to override (for absence of a better word) a function in the inner class of the parent class. Here is a good way of doing it:

class House {
public class Room {
public int minLength() {
return 100;
}
}

public Room getRoom() {
return new Room();
}
}

class Bungalow extends House {
public class Room extends House.Room {
@Override
public int minLength() {
return 1000;
}
}

@Override
public Room getRoom() {
return new Room();
}
}


Whenever you want to instantiate a Room of a House (either a House or a Bungalow), use the getRoom() method of the House.

Hence, following method shall print:

100
1000

on the screen:

public static void main(String args[]){
House h=new House();
System.out.println(h.getRoom().minLength());
h=new Bungalow();
System.out.println(h.getRoom().minLength());
}

No comments:

Post a Comment