instanceof
can be used to test if an object is a direct or descended instance of a given class. instanceof
can also be used with interfaces even though interfaces can't be instantiated like classes. Can anyone explain how instanceof
works?
First of all, we can store instances
of classes that implements a particular interface
in an interface reference variable
like this.
package com.test;
public class Test implements Testeable {
public static void main(String[] args) {
Testeable testeable = new Test();
// OR
Test test = new Test();
if (testeable instanceof Testeable)
System.out.println("instanceof succeeded");
if (test instanceof Testeable)
System.out.println("instanceof succeeded");
}
}
interface Testeable {
}
ie, any runtime instance that implements a particular interface will pass the instanceof
test
EDIT
and the output
instanceof succeeded
instanceof succeeded
@RohitJain
You can create instances of interfaces by using anonymous inner classes like this
Runnable runnable = new Runnable() {
public void run() {
System.out.println("inside run");
}
};
and you test the instance is of type interface, using instanceof
operator like this
System.out.println(runnable instanceof Runnable);
and the result is 'true'
object instanceof object_interface
will yield true
.
You do an instanceof
check of a reference
against an instance
, and it checks the type of instance
that particular reference
is pointing to.
Now since you can create a reference of an interface
, which points to an instance of implementing class
(same concept as, Super class reference
pointing to subclass instance
). So, you can do an instanceof
check on it.
For e.g :-
public interface MyInterface {
}
class ImplClass implements MyInterface {
public static void main(String[] args) {
MyInterface obj = new ImplClass();
System.out.println(obj instanceof ImplClass); // Will print true.
}
}
- First of all instanceof is used to compare whether the Object Reference Variable holding the object is of certain type or not.
Eg:
public void getObj(Animal a){ // a is an Object Reference Variable of type Animal
if(a instanceof Dog){
}
}
- In the case of interface
, the class
which implements it can be used with instanceof
.
Eg:
public interface Brush{
public void paint();
}
public class Strokes implements Brush{
public void paint(){
System.out.println("I am painting");
}
}
public class Test{
public static void main(String[] args){
Brush b = new Strokes();
if(b instanceof Strokes){
b.paint();
}
}
}
hi The below will yield True for the instanceOf:
• If S is an ordinary (nonarray) class, then:
• If T is a class type, then S must be the same class as T, or S must be a subclass of T;
• If T is an interface type, then S must implement interface T.
• If S is an interface type, then:
• If T is a class type, then T must be Object.
• If T is an interface type, then T must be the same interface as S or a superinterface of S.
• If S is a class representing the array type SC[], that is, an array of components of type SC, then:
• If T is a class type, then T must be Object.
• If T is an interface type, then T must be one of the interfaces implemented by arrays (JLS §4.10.3).
• If T is an array type TC[], that is, an array of components of type TC, then one of the following must be true:
- TC and SC are the same primitive type.
- TC and SC are reference types, and type SC can be cast to TC by these run-time rules
Please go to this link to have clear idea:
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.instanceof
public class Programmers {
public static boolean hasReallife(Programmer programmer) {
return programmer instanceof Reallife; ══════════════════╗
} ║
║
} ║
▼
public class ReallifeProgrammer extends Programmer implements Reallife {
public ReallifeProgrammer() {
diseases.get("Obesity").heal();
diseases.get("Perfectionism").heal();
diseases.get("Agoraphobia").heal();
}
@Override
public void goOut() {
house.getPC().shutDown();
wife.argue();
}
@Override
public void doSports() {
goOut();
BigWideWorld.getGym("McFit").visit();
}
@Override
public void meetFriends() {
goOut();
BigWideWorld.searchFriend().meet();
}
}
I know this is a very very old question with many good answers. I just want to point out the easiest (at least it is easiest to me) way to understand this operator.
If o instanceof t
returns true
, then
t castedObj = (t) o;
will not throw ClassCastException
, and castedObj
will not be null
.
This is important/useful if you want to access fields or methods from castedObj
later on - you know that by doing the instanceof
check, you will never have problems later.
The only downside is that this can be used for types without generics.
The instanceof operator will tell you if the first argument is an object that implements the second argument. Do not understand why it would matter that you can't directly instantiate the interface.
Integer num = 1;
if (num instanceof Number) {
System.out.println("An integer is a number!");
}
That's all you need.
来源:https://stackoverflow.com/questions/13487765/how-instanceof-will-work-on-an-interface