sorry for grave digging, just to make it clear for you, instanceof operator is primarily used to validate WildCasts , example you have a super "Appliance" ,and 2 sub classes of it "Tv" and "Radio"
Appliance Class:
/**
*
*@author Nader
*
**/
public abstract class Appliance {
public abstract void turnOn();
public abstract void turnOff();
}
Tv class:
/**
*
*@author Nader
*
**/
public class Tv extends Appliance {
private boolean on;
private float frequency;
@Override
public void turnOn()
{
on = true;
}
@Override
public void turnOff()
{
on = false;
}
public void changeFrequency(float freq)
{
frequency = freq;
}
}
Radio class:
/**
*
*@author Nader
*
**/
public class Radio extends Appliance {
private boolean on;
private int channel;
@Override
public void turnOn()
{
on = true;
}
@Override
public void turnOff()
{
on = false;
}
public void changeChannel(int chan)
{
channel = chan;
}
}
ShowUse , a class to show the proper and main usage of the instanceof operator :
import java.util.ArrayList;
/**
*
*@author Nader
*
**/
public class ShowUse {
public static void main (String[] argV)
{
//declare a list of the general type (Appliance)
ArrayList<Appliance> appliances = new ArrayList<Appliance>();
//adds 20 Tvs or Radios objects, randomly to the list , according to random numbers, either 1 or 0.
for(int = 0 ; i < 20 ; i++)
appliances.add((int)Math.random()*10==0?new Radio():new Tv());
//The real use of instanceof for casting validation
for(Appliance app : appliances)
{
System.out.println("this appliance is a " + ((app instanceof Tv)?"Tv":"Radio"));
if(app instanceof Tv)
{
Tv tv = (Tv)app;
tv.changeChannel(20);// call a function only found in the Tv class , after making sure that its type is a tv, other wise if it was a radio itll throw //runtime exception
}else{
Radio rad = (Radio)app;
rad.changeFrequency(99.1); //////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
}
Hope that helps ^^.