0

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 } 
Amani
  • 11
  • 1
  • 1
    Even if you cast it, the underlying object is still a Student. Each object basically has its own copy of the method if its class overrode it. Java uses something called dynamic dispatch for these instance methods, which basically means that the method to run is chosen at runtime. – user Jun 21 '20 at 15:43
  • 1
    I am just adding info to user's comment. The variable type lets you know what attributes and methods you have access to. The object type lets you know which class' methods will be called. – Jazz Jun 21 '20 at 15:48

1 Answers1

0

When you do,

public class Test2 {
  public static void main (String[] argus) {
    Person s1=new Student(4);
    Person s2=(Person)s1;
    s2.display(); // here it calls the method in the Student class!!
  }
}

Both s1 and s2 will have its ref class var and methods. i.e. s1 and s2 can only access name and display()

In Java an object's state and behavior is determined by it's ref. class to which it is assigned.

That is what you had done in Test1 and it worked :)

Even if you try Person s1=new Student(4); s1.getGrade() it won't work due to same reason.