I'm new to the java and I have a question about dynamic polymorphism. I created a class as follows. This is my superclass.
class Student{
protected String stuName;
Student(String stuName){
this.stuName = stuName;
}
public String getStuName() {
return stuName;
}
public void study(){
System.out.println("undergraduate");
}
}
I extend this class as follows, to take two subclasses.
class ScienceStudent extends Student{
ScienceStudent(String student){
super(student);
}
@Override
public void study() {
System.out.println("science undergraduate");
}
}
class ComputerStudent extends Student{
ComputerStudent(String stuName) {
super(stuName);
}
@Override
public void study() {
System.out.println("computer undergraduate");
}
}
Then after this is my main class.
public abstract class Main {
public static void main(String[] args) {
ScienceStudent scienceStudent = new ScienceStudent("jerry");
showName(scienceStudent);
Student student = new ScienceStudent("tom");
showName(student);
ComputerStudent computerStudent = new ComputerStudent("albert");
showName(computerStudent);
Student student1 = new ComputerStudent("lee");
showName(student1);
}
public static void showName(Student student){
System.out.println("Student :"+student.getStuName());
}
}
I created a method showName
to show the name of the students. I used its parameter type as Student
(the superclass type) Then after I instantiate the object as above. I want to know that is there any advantage by making object reference of the superclass and point it into the subclass
. That's mean what is the difference of
ScienceStudent scienceStudent = new ScienceStudent("jerry");
and
Student student = new ScienceStudent("tom");
I used both of two implementations, but both of them show same result for the showName
method
as follow.
Student :jerry
Student :tom
Student :albert
Student :lee
So what is the advantages of this one?
Student student = new ScienceStudent("tom");