Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I was expecting ClassCastException ?

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • 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
 
K. Tsang
Bartender
Posts: 3521
16
Android Java
  • Mark post as helpful
  • send pies
  • 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.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • 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.
 
indi man
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead this will give ClassCastException
A a=new C();
B b=(B)a;
C c=(A)b

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic