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());
}

Comments

Unknown said…
Very informative article.Thank you author for posting this kind of article .

http://www.wikitechy.com/view-article/nested-classes-in-java-with-example



Both are really good,.
Cheers,
Venkat