Calling Inherited Members of Class

Anna Scott
3 min readApr 12, 2022

Being Object Oriented Programming (OOP) language, new Java classes can build on existing classes via inheritance( inheritance is one of four foundational concepts of OOP, the other three are abstraction, encapsulation, and polymorphism). To show that class inherits from the other class the key word extends is used. In the code snipet bellow the class Dog inherits from the class Animal. Right now these classes are useless, because they are empty.

In the above class, class Dog is called a child class, and class Animal is called a parent class.

If parent and child classes are located in different packages then child class can call parent’s members (variables and methods) with the access modifiers public and protected. If parent and child classes are in the same package, then child classes have access to parent classes’ members with default access modifiers.

Please, check out the below code. Here we have three classes. The Dog class inherits public and protected instance variables from animal class. Our classes are in the same package, therefore our Dog class inherits method printInfo with default access modifier. In our Driver class we create a new object myDog and print information about it.

The output is

Grey has short fur

Lets move method printInfo() to class Dog. To reference the inherited instance variables, we can call them directly:

We can also access members of our classes using the key word this. Consider the following:

The output is:

Grey has short fur

We also can use key word super to access members of the parent class:

The output:

Grey has short fur

Child class does not have access to private members of parent class. The following code produces an error: age has private access in Animal.

However we can access private members indirectly. We can create a method that returns the value of private variable. In the code below, we have the method getAge() with the default access modifier returning private variable age:

The output:

Grey has short fur and is 7

Java classes may use protected and public members from parent classes, if they are in the same package it applies to members with default access modifier. Child classes can not access private members of parent class, however we could design methods that return private members.

Happy coding my friends!

All code could be found here:

--

--