How do parent classes function when one of their methods is redefined in a child?

When a child class overrides several methods and calls a method in its parent class, does the parent class use its own predefined methods or those that the child overrides?

In some context and example, my question stems from this question in the AP Computer Science Curriculum curriculum. Below, when super.act() is called, the act method of Dog calls eat() . Does the call to eat call the eat method in Dog or UnderDdog ?

Consider the following two classes.

 public class Dog { public void act() { System.out.print("run"); eat(); } public void eat() { System.out.print("eat"); } } public class UnderDog extends Dog { public void act() { super.act(); System.out.print("sleep"); } public void eat() { super.eat(); System.out.print("bark"); } } 

Suppose the following ad appears in the client program.

 Dog fido = new UnderDog(); 

What is printed as a result of calling fido.act() ?

  • run eat
  • run eat sleep
  • run eat sleep bark
  • run eat bark sleep
  • Nothing prints due to infinite recursion.
+4
source share
2 answers

There are two ways a subclass can call a superclass method:

  • Call the method defined in the superclass as your own, or
  • Call a method defined in the superclass that requests the behavior of the superclass

The syntax for the first method is as follows:

 act(); // it the same as this.act() 

The syntax for the second invocation method is as follows:

 super.act(); 

I think that now you have enough information to trace what is happening in your example, without any additional help.

+3
source

Whenever a method is called — either defined in a class hierarchy or some other unrelated class — polymorphism is triggered. The target method is executed to search from the actual instance class and move the inheritance hierarchy.

The only time this gets around is to call an overridden method from a method that overrides it with super .

0
source

Source: https://habr.com/ru/post/1411031/


All Articles