I'm trying hard to get this point. In Java I can use the Parent class type using the new operator with the Child class instance. Let's say that I have Parent Human class and Male and Female Child classes. I know that they are in a IS-A relationship, because a Male is-a Human and a Female is-a human. I know that only the methods that are defined in Human and overridden in Male/Female can be used with the Human type AND the Male/Female instance. But the question is: why would I want to use Human as the type of a Male/Female (child) instance?
I've tried a sample "Types" class that creates a Human type Male object. In order for the Male->humanType (or Female->humanType) method to work, I had to declare a Human->humanType method that does nothing. The only thing I could think of, is that by doing this I am able to pass a Human parameter to a method (method signature i.e. Human h1) that is both Male or Female, but in order fot this code to work, I have to declare in Human class ALL the methods that I declare in both Male/Female classes, that in Human class do nothing (similar to abstract methods).
class Types {
public static void main(String[] args) {
Types t1 = new Types();
Human p1 = new Male("Ugo");
t1.getHumanType(p1);
}
public void getHumanType(Human human) {
human.humanType();
}
}
class Human {
String name;
Human(String name) {
this.name = name;
}
public void humanType() { }
}
class Male extends Human {
Male(String name) {
super(name);
}
public void humanType() {
System.out.println("Im a Male");
}
}
class Female extends Human {
Female(String name) {
super(name);
}
public void humanType() {
System.out.println("Im a Female");
}
}
Is this a good way to run? I just want to understand better this kind of possibility that Java offers (I think it's called Late/Early binding), because I do not fully grasp it. Wasn't abstract class Human more correct?