+ 1

Inheritance in java

On net it is written that we can't access the grandparent's members directly but I am able to do it? So what does the statement means to say? class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ void weep(){System.out.println("weeping...");} } public class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }}

12th Jun 2018, 7:02 PM
harshit
harshit - avatar
5 Answers
+ 2
child class function cannot access it's grandparent function only when the function name of all 3 (i.e grandparent,parent and child function) is same. In this case to access grandparents function we need to call it from parents function using keyword super OTHERWISE THERE WON'T BE ANY PROBLEM
12th Jun 2018, 7:36 PM
Brajesh Kumar
Brajesh Kumar - avatar
+ 1
When a class extends a class, which extends another class then this is called multilevel inheritance. Class BabyDog extends class Dog and class Dog extends class Animal (superclass) BabyDog IS-A Dog, Dog IS-A Animal and therefore BabyDog IS-A Animal. BabyDog can access all public, protected and default (access modifiers!) from its superclass Dog or Animal. Considering Encapsulation in Java, all the data members of the class are private. You can only use setter and getter methods to set and get the data in it. The members of the superclass are private and despite subclass you have no access. Superclass Animal has only the method eat() with default access modifier and therefore subclass dog / Babydog can call it. For Example class Animal { private String animalProperty without getter() or setter() methods, subclass can not use it.
12th Jun 2018, 8:07 PM
asa22
0
we can access all the data members and the member functions of the ancestor(parents,grandparents....so on) from child class if it is public, protected or default. WILL U SEND ME THE LINK FEOM WHERE U READ THIS WRONG CONCEPT?
12th Jun 2018, 7:17 PM
Brajesh Kumar
Brajesh Kumar - avatar