Sunday, June 12, 2011

How to force the subclasses of a concrete class to override a method?

There is no such real world scenario where a concrete entity will want to force a more specific entity to override its method. If it is to be overridden then why not make the super class as abstract.

Anyways, the logic behind the interview questions being asked now a days is something which requires best talent from the psychology field.

Solution: The solution which I have come up with for the above Java Interview question is to use the instanceof operator in the super class and throw an exception if the instance on which method is being invoked is found to be of the sub class. The sample program showing this scenario follows:

Though still its not like generating compile time error but gives exception at runtime.  Do suggest if you have a better solution.

public class Test{

   void test() {
    if ((this instanceof Test1)) {
     throw new RuntimeException();
    }
    System.out.println("passed");
   }
   
   public static void main(String[] args) {
    Test t1 = new Test();
    Test1 t2 = new Test1();
    
    t1.test();
    t2.test();
   }
 
}
class Test1 extends Test {

}

The output of above program is:
passed
Exception in thread "main" java.lang.RuntimeException
 at Test.test(Test.java:5)
 at Test.main(Test.java:15)

No comments:

Post a Comment

Chitika