开发者

Java instantiate class from string

开发者 https://www.devze.com 2023-02-14 08:07 出处:网络
I have the following, public interface SuperbInterface public class A implements SuperbInterface public class B extends A

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开发者_如何学C().
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 ?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号