Downcasting problem


P

parkarumesh

I have below example. It compiles fine but gives classcast exception at
run
time. Just curious why Java prohibit down casting.

public class C {
public static void main (String a[]){
B b = (B) new A();
}
}
class A {
public void draw (){
System.out.println("1");
}
public void draw1 (){
System.out.println("2");
}

}
class B extends A {
public void draw (){
System.out.println("3");
}
public void draw2 (){
System.out.println("4");
}
}

/*
also in a class hierarchy which is larger object, the base class or the
derived class? If it is base class, Why?
*/
 
Ad

Advertisements

P

Paul Hamaker

B ISA A, but NOT A ISA B, how would you call draw2() if it's
simply not there ?
new A is just that, an A with its limited capabilities, draw() and
draw1() .
 
P

parkarumesh

Paul said:
B ISA A, but NOT A ISA B, how would you call draw2() if it's
simply not there ?
new A is just that, an A with its limited capabilities, draw() and
draw1() .

Ok fine, just comment out draw2, and even the problem
remains.................
 
B

Bart Cremers

It has nothing to do with the methods available.

B extends A, so B is an A and a B.
A extends nothing (well, Object that is) so A is an A an not a B.

A a = new B(); // Works
B b = (B) a; // Works;
B anotherB = (B) new A(); // Fails

See it like this.

class Shape {}
class Rectangle extends Shape {}
class Circle extends Shape {}
class Triangle extends Shape {}

You can tell that every Rectangle is also a Shape, but not every Shape
is a Rectangle. Some will be Circle and Triangle.

Shape r = new Rectangle(); // Works
Shape c = new Circle(); // Works
Rectangle rect = new Circle(); // Will never compile, because it just
doesn't make sense
Rectangle r = (Rectangle) c;// Will fail at runtime, because c is not a
rectangle.

Regards,

Bart
 
Ad

Advertisements

T

tom fredriksen

Ok fine, just comment out draw2, and even the problem
remains.................

To expand a bit:

class A consists of only things defined in A.
class B consists of things defined in A and B.
So A can only be A, but B can be both A and B.

In other words "references must be the same or from a super class" for
it to work, which means that the reference can hold any objects of sub
class type. You can not do it the other way around.

If you had done the following, the down casting would have worked:

B b = new B()
A ab = b;
B b2 = (B)ab;

So what you need to do is either do a new B() or redefine it to be an A
reference.

/tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top