Reputation: 41
Let's says I have 5 classes, 1 superclass and 4 subclasses. My superclass is Animal
and has Species
and Charateristic
, these 2 will be inherited to my subclasses.
4 subclasses are: Lion
, Eagle
, Bee
, and Whale
( these 4 subclasses extend Animal
). These subclasses will have methods Voice()
and Walk()
.
The question is, that my mentor told its student:
case 1. If this program is running it is launched, there will be a menu that shows that 4 subclasses / Animal
objects.
case 2. After the user has chosen an animal, for example: Eagle
. Then it shows what voice and movement an eagle has.
case 3. If the user chooses exit, then terminate the program.
In this case, we will use switch + case
, right? But then my question is how do I call these 4 subclasses from my superclass?
If I add public static void main
inside each of the subclasses, then these 4 subclasses become a main
method, and I'm unable to set or create it with switch
case. Or do I have to create another class that extends those 4 subclasses and call it?
Thank you, I hope you've understood what I mean :)
Upvotes: 0
Views: 121
Reputation: 6066
You should access the subclass methods through virtual method calls (on a reference typed to the superclass). You can use Factory design pattern as well. Can be something like this:
int choice;
// read the choice, if exit chosen then exit
// getAnimal returns the actual animal instance
// (either a new instance or an existing one from internal registry)
// can select by switch() inside
Animal *animal = getAnimal(choice); // or Animal::getAnimal(choice), etc.
if (animal == null) {
System.err.println("Invalid choice");
} else {
// will call the methods on the actual specific animal retrieved by getAnimal()
animal.Voice();
animal.Walk();
}
Neither Animal nor the animal kinds should have main() - only the actual application which handles the entire logic (that could be the Animal class as well, but maybe better to create a separate class for the application itself).
EDIT: This is how the getAnimal()
method could look like:
Animal * getAnimal(int choice)
{
switch (choice)
{
case 1:
return new Lion();
case 2:
return new Eagle();
// etc.
default:
// invalid choice
return null;
}
}
Upvotes: 1
Reputation: 230
At some point you have to create your animal instances
Animal a1 = new Lion();
Animal a2 = new Eagle();
System.out.println(a1.Species());
System.out.println(a2.Species());
Create a separate class to control your program containing main e.g.
public class MyClass {
public static void main(String[] args) {
int opt = 1; // TODO - use args
switch (opt) {
case 1:
Lion obj = new Lion();
System.out.println("Voice: " + obj.Voice() + ", Walk: " + obj.Walk();
break;
case 2:
Eagle obj = new Eagle();
System.out.println("Voice: " + obj.Voice() + ", Walk: " + obj.Walk();
break;
// etc
}
}
}
Upvotes: 1