The problem is to call Honda class display method. Which class method will be called depends upon the string variable that will be passed at runtime. Here I have used one parent class of Honda so that I can achieve runtime polymorphism. But then I am getting ClassNotFoundException even that is included in the throws clause of main. Unable to figure what to do.
Here is the code of all the three classes which are there in the same package.
Vechicle.java
package com.company;
public class Vehicle {
public void display() {
System.out.println("Random text");
}
}
Honda.java
package com.company;
public class Honda extends Vehicle{
public void display()
{
System.out.print("honda called");
}
}
Main.java
package com.company;
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
String className = "Honda";
Class cls = Class.forName(className);
Vehicle v = (Vehicle) cls.getDeclaredConstructor().newInstance();
v.display();
}
}
The error which I am getting is :
Exception in thread "main" java.lang.ClassNotFoundException: Honda
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:315)
at com.company.Main.main(Main.java:10)
I think I need to handle the ClassNotFoundException in Honda class also but extends and throws can't work simultaneously. Please help me in finding the issue.