Showing posts with label instanceof. Show all posts
Showing posts with label instanceof. Show all posts

Saturday, 11 June 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)

Sunday, 22 May 2011

The instanceof operator in java

The instanceof operator is a binary operator that determines whether an object reference (the left operand) is an instance of the class, interface, or array type specified by the right operand. The instanceof operator cannot be used with primitive types (this results in a compilation error).

The instanceof operator returns a boolean value of true if the left operand references a non-null object of class C (or array of type T), so that at least one of the following conditions holds.
  • The right operand is a class name C' and C is a subclass of C'.
  • The right operand is an interface name I, and C implements I.
  • The right operand is an array of type T', the left operand is an array of type T, and T is a subclass or subinterface of T' or equal to T'.
The instanceof operator returns false if none of the above conditions are met or if the left operand is null.

String s = "abcd";
Vector v = new Vector();
v.add(s);
Object o = v.elementAt(0);
System.out.println(s instanceof String); // 1.true
System.out.println(s instanceof Object); //2.true
//because String is subclass of Object class
System.out.println(o instanceof String); //3.true
System.out.println(o instanceof Object); //4.true
System.out.println(o instanceof Vector); //5.false


The third output line displays a value of true even though o is declared to be of type Object. How is this so? That's because the object assigned to o is the String object that was added to Vector v.
The fourth and fifth output lines result from the fact that a String object is an Object object but not a Vector object.

Tuesday, 17 May 2011

Avoid excessive use of the instanceof operator

Many hold that the instanceof operator should be used only as a last resort, and that an overridden method is usually (but not always) a better alternative.

This is because, if one object is of type T1, it wouldn't guarantee that object T2, which returns True in case of (T2 instanceof T1), may be of type T1. This is because T2 may belong to subclass of T1, as instanceof returns true than as well. See how we used it in equals method.

Friday, 22 April 2011

Casting Objects and instanceof

One of the difficulties of using a superclass array to hold many instances of subclass objects is that one can only access properties and methods that are in the superclass (ie. common to all). By casting an individual instance to its subclass form, one can refer to any property or method. But first take care to make sure the cast is valid by using the instanceof operator. Then perform the cast. As an example using the above Animal class:

if (ref[x] instanceof Dog) // ok right type of object
{
  Dog doggy = (Dog) ref[x]; // cast current instance to subclass
  doggy.someDogOnlyMethod();
}


Casts to subclass can be done implicitely but explicit casts are recommended. Casts to superclass must be done explicitly. Casts cannot be made between sibling classes.