• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Regarding object casting

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Given an Example like this

class A {
void method() {
System.out.println("A");
}
}

class B extends A{
void method() {
System.out.println("B");
}
}

class Mock1 {
public static void main(String [] args) {
B b = new B();
A c = (A) new B();
c.method();
}
}

The output I got is B.

But inside the main() method if i have a code like this,
B b = new B();
A c = (B) new A();
c.method();

This code compiles fine, but I am getting a java.lang.ClassCastException when I try to run this code.

Can anyone explain this behaviour.
Thanks in advance.
 
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can cast up and inheritance tree with out any problem. Say you have a derived class object. You can cast it up in the inheritance tree. you can also cast it to Object. But when you have a base class object you will not be able to cast it down the inheritance tree. You will be able to compile it but the code will throw a ClassCastException. You can go through the JLS regarding this.
 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ! I do not understand why I can not cast down the inheritance tree .
Please take a look at this code , and look at line 4 :

interface I1 {}
interface I2 {}
class Base implements I1 {}
class Sub extends Base implements I2 {}
class Yellow {
public static void main(String args[]) {
Base base = new Sub(); // 1
I1 i1 = base; // 2
Sub sub = (Sub)base; // 3
I2 i2 = (Sub)base; // 4
}}

this compile and run fine !
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You must note that in your first example, B is a A, but you cant say A is a B, so you cant cast from A to B.

The second example is OK because object base is instance of Sub. Then it implements both interfaces and also is a Base.

Regards..
reply
    Bookmark Topic Watch Topic
  • New Topic