Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java instantiate class from string

Tags:

java

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();
like image 670
Rosdi Kasim Avatar asked Mar 03 '11 08:03

Rosdi Kasim


2 Answers

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?

like image 173
Suraj Chandran Avatar answered Sep 28 '22 01:09

Suraj Chandran


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.

like image 33
TofuBeer Avatar answered Sep 27 '22 23:09

TofuBeer