I have the following classes:
public abstract class A implements C {
...
}
public abstract class B extends A {
method();
}
But when I try to do the following
A a = null;
A a = new A();
((B) a).method();
I receive a ClassCastException, does anyone have a solution?
B extends A, but A doesnt extend B.
everything A has B has, but A cant do the stuff declared in B
An instance of B
is an instance of A
, but an instance of A
is not necessarily a B
. Similar to saying "all circles are shapes, but not all shapes are circles".
You can't do what you are trying to do. That's why you get the exception.
I think what you want here is a constructor to take and A object and make a larger B object out of it which has the included method (which A does not have). But that doesn't make a whole lot of sense. Cant think for the life of me why you would want to do this in practice, and wouldn't just build the B object to start with.
public abstract class A implements C {
...
}
public abstract class B extends A {
public B(A child){
//Construct a B out of A here
}
public void method();
}
Then
A a = null;
A a = new A();
new B(a).method();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.