why jave do the casting in the Test1 class but don't in the Test2? in the Test1 class when I did casting compiler works fine when I invoked getGrade() method. but in the Test2 class, I did casting but the reference variable still references to an object of type Student?! why is that?
1 public class Test1{
2 public static void main (String[]argus){
3 Person s1=new Student(4);
4 Student s2=(Student) s1;
5 s2.getGrade();
6 }}
7
8 interface Person{
9 String name="Amani";
10 public void display();
11 }
12
13 class Student implements Person{
14 int study_level;
15 double grade;
16 public Student(int study_level ){
17 this.study_level=study_level;
18 }
19 public void display(){
20 System.out.println("name="+name+" level= "+study_level);
21 }
22 public void getGrade(){
23 System.out.println("Grade= "+grade);
24 }
25 }
Outputs:
Grade= 0.0;
1 public class Test2{
2 public static void main (String[]argus){
3 Person s1=new Student(4);
4 Person s2=(Person)s1;
5 s2.display(); // here it calls the method in the Student class!!
6 }}
7
8 class Person{
9 String name;
10 public void display(){
11 System.out.println("name="+name);
12 }
13 }
14
15 class Student extends Person{
16 int study_level;
17 double grade;
18 public Student(int study_level ){
19 super();
20 this.study_level=study_level;
21 }
22 public void display(){
23 super.display();
24 System.out.println(" level= "+study_level);
25 }
26 }