J
James
I was playing around with a polymorphism today and I'm confused on how
I achieved my desired results. I know I shouldn't question if it
works, but I'd like to know why it works.
Given two classes, a Traveler and an Agent. Both inherit the abstract
Person class.
Login.class:
public static Person setLogin(int selector) {
Person person = null;
if (selector == 0) {
Traveler traveler = new Traveler();
traveler.setTravelerID("12345");
person = traveler;
} else {
Agent agent = new Agent();
agent.setAgentID("av333-33");
person = agent;
}
return person;
}
So when this method is called, it instantiates either an agent or
traveler and returns that object to the caller. But the return type
is Person.
TestLogin.class:
public static void main(String[] args) {
Traveler traveler = (Traveler)Login.setLogin(0);
System.out.println(traveler.getTravelerID());
}
The result printed is "12345". Which is correct.
Where I am confused is why the Traveler class properties were not lost
when it was assigned to a type Person in the Login.class [person =
traveler;]
Since the Person class does not have "travelerID", why would it not
have been chopped off?
Thanks for any assistance!
James
I achieved my desired results. I know I shouldn't question if it
works, but I'd like to know why it works.
Given two classes, a Traveler and an Agent. Both inherit the abstract
Person class.
Login.class:
public static Person setLogin(int selector) {
Person person = null;
if (selector == 0) {
Traveler traveler = new Traveler();
traveler.setTravelerID("12345");
person = traveler;
} else {
Agent agent = new Agent();
agent.setAgentID("av333-33");
person = agent;
}
return person;
}
So when this method is called, it instantiates either an agent or
traveler and returns that object to the caller. But the return type
is Person.
TestLogin.class:
public static void main(String[] args) {
Traveler traveler = (Traveler)Login.setLogin(0);
System.out.println(traveler.getTravelerID());
}
The result printed is "12345". Which is correct.
Where I am confused is why the Traveler class properties were not lost
when it was assigned to a type Person in the Login.class [person =
traveler;]
Since the Person class does not have "travelerID", why would it not
have been chopped off?
Thanks for any assistance!
James