• 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

I was expecting ClassCastException ?

 
Ranch Hand
Posts: 391
1
MySQL Database PHP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why this does not result in ClassCastException

class A{}
class B extends A{}
class C extends B{}
class Test1
{
public static void main(String args[])
{
A a=new C();
A a1=(B)a;
}
}

a is referencing to a C Object , trying to cast in B should have result in exception
 
Bartender
Posts: 3648
16
Android Mac OS X Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok your class setup says C is a B and B is a A, which makes C is a A.

The main says variable a is a C (which we know is a B). Then variable a1 cast this to a B (variable a's parent class B which is a A).

You should try down-casting... then ClassClassException should throw. I let you figure out the code to test that.
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mahtab Alam wrote:a is referencing to a C Object , trying to cast in B should have result in exception


A C IS-A B (because C extends B), so the cast is fine.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instead this will give ClassCastException
A a=new C();
B b=(B)a;
C c=(A)b

 
expectation is the root of all heartache - shakespeare. tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic