0

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:)

4
  • You get an error because obj is a variable of type Object and Object does not have a method called getDescription() Commented Nov 2, 2020 at 10:39
  • I mean this could happen to p.getDescription() right? Sorry Something I need to add is that Person does not have the method called getDescription() Commented Nov 2, 2020 at 10:43
  • 1
    What you just said is literally impossible. If the line p.getDescription() above compiles correct then the Person class (Or Interface) does have a method called getDescription(). That's how Java and its compilers work.... Commented Nov 2, 2020 at 10:45
  • A extending B does not mean B extends A. And A and B cannot simultaneously extend each-other. (cyclic dependency) Commented Nov 2, 2020 at 11:04

1 Answer 1

1

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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.