Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Refernce casting

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

}
}
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You had your fun. Now it's time to go to jail. Thanks for your help tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic