I have two classes, Dog and Cat:
class Dog{
public void speak(){
System.out.print("Woof!");
}
}
class Cat{
public void speak(){
System.out.print("Meow!");
}
}
In my main, I take the name as String, either "Cat", or "Dog".
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String name = sc.next();
Class<?> cls = Class.forName(name);
Object object = cls.newInstance();
}
But now I want to be able to call the method "speak". But then I have to cast the object to either cat or dog, since "Object" obviously does not have built in "speak" method. So my solution was to make another class (I can't use if-statements btw):
class Animal{
public void speak(){
}
}
And then both "Cat" and "Dog" can extend Animal and override its methods. Is there any other way to do this WITHOUT making another method / using if-statements? (Including switch case, ternary operator). Thanks in advance.
ANOTHER QUESTION: If I take in the name of the METHOD in as an input as well, how would I call it? For example:
class Dog{
public void speak(){}
public void bark(){}
}
If I take in as a String either "speak" or "bark", how would I call the method without using if-statements?
Animaland overridespeak(). Where do you need a control structure?