Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Refernce casting  RSS feed

 
komal sutaria
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!
Everyone

With below code I was trying to understand reference casting but I think I got confused. Can any one please explain me why d6 d7 thows ClassCastException() and how to takle ref casting at runtime?

package practice;

class Bbase{}
class Dderived extends Bbase{}
class Ddderived extends Dderived{}



public class Test
{
public static void main(String[] args)
{

Bbase b = new Bbase();
Dderived d = new Dderived();
Bbase b1 = new Dderived();
Bbase b2 = new Ddderived();
Dderived d2 = (Dderived)b2;
Dderived d3 =(Dderived) b1;
Dderived d4 = (Ddderived)b2;
Ddderived d5 = (Ddderived)b2;
Bbase d8= (Bbase)d;
//Ddderived d6 = (Ddderived)b; error
//Ddderived d7 =(Ddderived) b1; error

}
}
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The true runtime type of an object is set when it's instantiated with "new."

In the above example, the object referenced by b has a true runtime type of Bbase, and the object referenced by b1 has a true runtime type of Dderived. Neither of these are instances of Ddderived, which is why the casts fail.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!