bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

Downcasting and instanceof operator

 

Downcasting

When child class refers to the object of Parent class then it is known as downcasting. If you perform it directly then it gives compilation error so typecasting is used to perform downcasting but ClassCastException is thrown at runtime.

e.g.

class Flower {

}

class Rose extends Flower {

static void smell(Flower f) {

Rose r = (Rose) f; //downcasting using typecasting

System.out.println("Downcasting is performed");

}

public static void main (String [] args) {

Flower f=new Rose();

Rose.smell(f);

}

}

Output

Downcasting is performed

 

instanceof Operator – Using instanceof operator you can test the object is an instance of specific class type or not.  That means you can compare instance with particular type. It returns true or false. So it is also a comparison operator.

e.g.

class Intellipaat{

public static void main(String args[]){

Intellipaat in=new Intellipaat();

System.out.println(in instanceof Intellipaat); /* It returns true because object i is an instance of class Intellipaat */

}

}

Output

true

 

Downcasting with instanceof Operator 

Downcasting is performed using instanceof operator without throwing any exception.

e.g.

class Flower {

}

public class Rose extends Flower {

static void smell(Flower f) {

if(f instanceof Rose ){

Rose r=(Rose)f; //downcasting

System.out.println("Downcasting is perfromed with instanceof operator");

}

}

public static void main (String [] args) {

Flower f=new Rose();

Rose.smell(f);

}

}

Output

Downcasting is perfromed with instanceof operator

Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

"0 Responses on Downcasting and instanceof operator"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 05th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free Downcasting and instanceof operator.