简体   繁体   中英

Java instantiate class from 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 instantiate C but I seems to be getting 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();

The only thing I can think of is that you haven't overridden doWork() in C.

Maybe you have tried ot override but with some spelling mistake in method name or wrong parameters?

Assuming you are using a newer version of Java add @Override to the doWork method. If you have incorrectly overriden the method the compiler will then let you know.

Are you sure that C overrides the doWork method? Based on the question as it is posed it is perfectly reasonable/legal to expect that as part of extending B , C does not provide its own implementation for doWork and instead relies on the one provided the superclass B .

I see the outcome:

A's do work

whats the things you are expecting ?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM