Possible to add a new class that can be cast to an existing final class?

56 views Asked by At

I have class A defined in a library:

 public final class A {blah}

And then I want to hack it somewhere using a new class B to substitute it:

A a = new A();  
A a = (A) new B();

B has all the methods and members in A, so it's actually safe to do this, and I can do it in C++. But for Java, this casting will result in an exception. So is there any workaround or hacking to do this in Java? In addition, is there a way to hack without touching the VM?

3

There are 3 answers

0
Razib On BEST ANSWER

Though B has all the methods and property dose A have, you can not cast object of B to a reference of A. That means -

A a = (A) new B(); 

is invalid unless B extends A.

And here A is a final class so you can not extends A by B. You have to make A non-final and B has to extends A. Then the above casting will be valid.

3
D.Shawley On

Java's final keyword exists to prevent sub-classing so the simple answer is no. You could employ something like PowerMock to do this sort of thing. I wouldn't do it outside of testing though.

0
tamaramaria On

This is not possible, because your class A is final. A final class is simply a class that can't be extended.