Page 1 of 1

About Question enthuware.ocpjp.i.v11.2.1359 :

Posted: Thu Jul 09, 2020 11:26 am
by victor2016
httpatomoreillycomsourceoreillyimages2248725.png.jpg
httpatomoreillycomsourceoreillyimages2248725.png.jpg (74.12 KiB) Viewed 940 times
Hi,

I'm reviewing my knowledge in inheritance (worked with Java for 13 years but never made use of it) so I'm a bit rusty, sorry :oops:

I am looking over Head First Java chapter on "Designing with Inheritance" (please see attached). According to the picture, subclasses like Lion and Tiger seem to be able to inherit methods two levels up. The inheritance design seems to be as:

class Animal (class A)
class Feline extends Animal (class B extends A)
class Lion extends Feline (class C extends B)

And methods like makeNoise() and eat() from Animal (class A) seem to be accessible to class Lion (class C).

The design seem to be analogous to the design in this question and methods in class A seem to be accessible to methods in class C on the picture. Why is perform_work() method of A not accessible to class C in this question? Please, help me understand this. Am I missing something?

Thank you,
Victor.

Re: About Question enthuware.ocpjp.i.v11.2.1359 :

Posted: Thu Jul 09, 2020 11:58 am
by admin
How would a class access its grandparent's version of a method if the parent has overridden that method? Can you can write a small test progarm and show it here?

Things may seem the same in the book and this question but the devil is always in the details. I can't really comment on what the book is talking about but I am sure there is some difference between the two scenarios .

Re: About Question enthuware.ocpjp.i.v11.2.1359 :

Posted: Thu Jul 09, 2020 12:59 pm
by victor2016
Hi,

I wrote what I think is modelling question's concept:

Code: Select all

class A
{
        public void perform_work()
        {
                System.out.println("Class A");
        }
}

class B extends A
{
        public void perform_work()
        {
                System.out.println("Class B");
        }
}

public class C extends B
{
        public static void main(String [] args)
        {
                A type = new C();
                type.perform_work();
        }
}
When I run it, it get printout "Class B" which means the method being accessed is one level up. When I disable method of Class B, I get printout "Class A". So just as in the picture class Lion uses Animal's makeNoise() because class Feline doesn't have it. But if Feline did have it then class Lion would have used Feline's makeNoise()?

Thanks,
Victor.

Re: About Question enthuware.ocpjp.i.v11.2.1359 :

Posted: Thu Jul 09, 2020 2:08 pm
by admin
Right, so, I think you got your answer. In the code given in this question, A , B, and C all have perform_work method, which makes it impossible for perform_work() method of A to be called from an instance method in C.