> B ISA A, but NOT A ISA B, how would you call draw2() if it's
> simply not there ?
[quoted text clipped - 4 lines]
> Paul Hamaker, SEMM, teaching ICT since 1987
> http://javalessons.com
Ok fine, just comment out draw2, and even the problem
remains.................
Bart Cremers - 17 Mar 2006 08:56 GMT
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
tom fredriksen - 17 Mar 2006 11:57 GMT
> 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