Why can this object access the methods of this parent class?

This question is taken from the AP Computer Science practice test.

public class Bird
{
    public void act()
    {
        System.out.print("fly"); 
        makeNoise(); 
    }
    public void makeNoise()
    {
        System.out.print("chirp"); 
    }
}

public class Dove extends Bird
{
    public void act()
    {
        super.act(); 
        System.out.print("waddle"); 
    }
    public void makeNoise()
    {
        super.makeNoise(); 
        System.out.print("coo"); 
    }
}

Assume that in a class other than Bird or Dove, the following declaration appears:

Bird pigeon = new Dove(); 

What is printed as a result of the call pigeon.act()?

I thought the answer would be “fly tweet”, but the textbook says the answer is “chirpa fly coo waddle”. I thought a pigeon could only access methods available in Bird? I got the impression that if a user wants to access methods in Dove, the “dove” should be thrown into Dove.

Will it Bird pigeon = new Bird();give the same result? How about Dove pigeon = new Dove();?

+4
4

" , " " , Bird? , Dove," " Dove". true.

mssing .

  • Bird pigeon = new Dove();, Dove extends Bird, Dove, - Bird. Dove, , , , .

  • - overriden . Overriden , , . . , , , . Dove overriden.

  • super, , () ( ) . super , , . , . , , . ( ), , . - super . Sub class , .

  • , , - Dove (Sub class), Bird (Super class), Dove.

+1

, act pigeon Dove.

, "" , Bird?

, , , , , . , act Bird, pigeon, .

. , , pigeon. , Dove Bird, , Bird. .

Bird pigeon = new Bird(); ?

, , pigeon , .. Bird, Bird.

+4

, . , ; , .

act() Dove; super; "".

makeNoise()... " ". , : "" - ""; , Dove! ""!

Dove; "waddle".

: , , , , .

, . : ; ; , !

+2
  • Dove act makeNoise Bird. ( Dove). , public protected package private, , .
  • pigeon Dove.
  • pigeon.act() Dove.act.
  • Dove.act super.act, Bird.act.
  • Bird.act fly makeNoise pigeon, Dove.makeNoise.
  • Dove.makeNoise super.makeNoise, Bird.makeNoise.
  • Bird.makeNoise print chirp.
  • Dove.makeNoise coo super.makeNoice
+2
source

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


All Articles