I'm currently learning polymorphism in Java, and part of the assignment was to create a program that will print out various subclasses using inheritance and polymorphism. I have tried looking for solutions but I couldn't seem to find anyone else experiencing this issue.
Below is a piece of code that is supposed to print Alex
and Alexa
respectively. However, the output is, instead, Alexa
Alexa
.
I have tried debugging by stepping through using Eclipse, but I can't pinpoint what is the mistake. I am truly stumped at this point, I've been trying this question for the past week but to no avail. Please forgive me if this is a simple question but I can't figure out what went wrong. I would truly appreciate any assistance!
import java.util.ArrayList;
public class Human {
protected static String name;
public Human(String name) {
System.out.println("In human constructor");
this.name = name;
}
void greetings() {}
static void print(Human human) {
System.out.println(name);
}
public static void main(String[] args) {
ArrayList<Human> human = new ArrayList<Human>();
human.add(new Man("Alex"));
human.add(new Woman("Alexa"));
for (int i = 0; i < human.size(); i++) {
print(human.get(i));
}
}
}
class Man extends Human {
public Man(String name) {
super(name);
// TODO Auto-generated constructor stub
}
}
class Woman extends Human {
public Woman(String name) {
super(name);
// TODO Auto-generated constructor stub
}
}