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:)
obj is a variable of typeObjectandObjectdoes not have a method calledgetDescription()p.getDescription()above compiles correct then the Person class (Or Interface) does have a method calledgetDescription(). That's how Java and its compilers work....