I want to create dynamic object so that I call the respective method of the class. All classes and interface is in different file but under the same folder Given:
interface Method
{
public void display();
}
class Car implements Method
{
public void display()
{
System.out.print("Car method");
}
}
class Honda implements Method
{
public void display()
{
System.out.print("Honda method");
}
}
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
String className = "Car";
Class cls = Class.forName(className);
Method method = (Method) cls.getConstructor().newInstance();
method.display();
}
}
Now if pass Honda in the string then I want to string method to get called but if I pass Car in string then I want to get Car method as an output but after compilation this method is not getting called. There is no error but no expected output as well. How to get the desired output. Please help.