Erik.Z
Erik.Z

Reputation: 59

Java Object Class Dynamic Binding

if I have the following code as below, so the Employee is a subclass of Person, my question is that when we call p.getDescription(), it would do the dynamic binding to find call the getDescription() method that the p points to which is an Employee object. And Person class does NOT have the method called getDescription(). The only Employee Class implements the getDescription() method.

But when we call obj.getDescription() why we would get an error? Does not all the class in java extends the Object class , so why when we call obj.getDescription() it would not just do the dynamic binding and find out that the object that it is referring to is actually an Employee object and then call its method accordingly?

When we cast the obj to Employee then it is fine, which is understandable

Thank you Erik

Person p = new Employee("erik", 5000, 1989,04,16);
Object obj = new Employee("erik", 5000, 1989,04,16);
 
System.out.println(p.getDescription()); // get the description of the Employee
System.out.println(obj.getDescription()) // error
System.out.println(((Employee)obj).getDescription()); // OK

Thank you all for the answer , it turns out that in the original code I thought the Person does not implement the getDescription() , but I was mistaken(that's why I have asked this question) ,there is a abstract method in Person of:

public  abstract String getDescription()

That's why p.getDescription() was working, All good now:)

Upvotes: 0

Views: 166

Answers (1)

Shamoon97
Shamoon97

Reputation: 329

Does not all the class in java extends the Object class Yes Every Class in Java by default extends the Object class. But your case is different you are explicitly making Object obj=new Employee(). This is actually making the object of Employee class in which there is no function like obj.getDescription()

Upvotes: 1

Related Questions