Java instance of a class from a string

I have the following:

public interface SuperbInterface public class A implements SuperbInterface public class B extends A public class C extends B 

I want to create an instance of C , but I seem to get B , what did I do wrong?

 Class classz = Class.forName("C"); SuperbInterface superb = (SuperbInterface)classz.newInstance(); //Here when I debug it seems to be going to B.doWork() methods instead of C.doWork(). superb.doWork(); 
+7
source share
4 answers

The only thing I can think of is that you did not redefine doWork () in C.

Perhaps you tried to cancel, but with some spelling error in the method name or incorrect parameters?

+5
source

Assuming you are using a newer version of Java, add @Override to the doWork method. If you override the method incorrectly, the compiler will inform you of this.

+1
source

Are you sure C overrides the doWork method? Based on the question posed, it is quite reasonable / legal to expect that, within the framework of the extension, B C does not provide its own implementation for doWork and instead relies on the one that was provided to superclass B

0
source

I see the result:

A do work

what do you expect

0
source

All Articles