![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
In hierarchical inheritance, There is only one Base class which is accessed by multiple Derived classes
In fig, Class A is the Base class and Class B,C,D are the three derived classes. There can be any number of child classes which can be able to access the properties of parent class.
Consider, There are three peoples who want to make a Juice,Tea and Soda by using water. For these 3 items a water is a common element to use. We call water as Base class and Juice,Tea,Soda are the three Derived classes who they want to use the water for three different purposes. This is called as Hierarchical Inheritance.
class BaseClass { body of BaseClass } class Derived1 extends BaseClass { body of Derived1 } class Derived2 extends BaseClass { body of Derived2 } . . class DerivedN extends BaseClass { body of DerivedN }
Example to show the use of Hierarchical inheritance. We will use the existing water string into three different classes.
class Water { String pot = "Water"; } class Juice extends Water { String getWater; Juice() { getWater = super.pot; System.out.println(getWater+" is required for making Juice"); } } class Tea extends Water { String getWater; Tea() { getWater = super.pot; System.out.println(getWater+" is required for making Tea"); } } class Soda extends Water { String getWater; Soda() { getWater = super.pot; System.out.println(getWater+" is required for making Soda"); } } class MainClass { public static void main(String args[]) { Juice myJuice = new Juice(); Juice myTea = new Tea(); Juice Soda = new Soda(); } }