06 Aug Java Inheritance
The Inheritance concept in Java brings the code reuse functionality by using the inherit feature. This allows a class to inherit the members of a class already present. Therefore, the concept of base and derived class is what Inheritance is all about in Java.
Before moving further, let us first understand the concept of Inheritance with the base can derived class:
- Base class: The base class is the parent class.
- Derived class: The derived class is the child class since it is derived from the parent class.
We will use the extends keyword to inherit. Let us say our super class is Father and sub class Kid:
1 2 3 4 5 |
class Kid extends Father { // code } |
Let us now see an example of Inheritance wherein we will create a Derived class from a Base class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Parent class class Father { public void demo1() { System.out.println("This is the parent class"); } } // Child class class Kid extends Father { public void demo2() { System.out.println("This is the child class"); } public static void main(String args[]) { Kid obj = new Kid(); /* Using extends keyword, the Kid (sub class) class inherits the method demo1() of the Father class (super class). */ obj.demo1(); obj.demo2(); } } |
Output
1 2 3 4 |
This is the parent class This is the child class |
Let us now inherit the attributes and methods from the Parent class. We have set the fname to a protected modifier so that it is even accessible in the subclass Kid:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Parent class class Father { protected String fname = "Ramesh"; public void demo1() { System.out.println("This is the parent class"); } } // Child class class Kid extends Father { private String sname = "Sachin"; public void demo2() { System.out.println("This is the child class"); } public static void main(String args[]) { // A subclass object Kid obj = new Kid(); /* Using extends keyword, the Kid (sub class) class inherits the method demo1() of the Father class (super class). */ obj.demo1(); obj.demo2(); // Displaying the value from the Parent class with the attribute fname // Displaying the value from the Kid class with the attribute sname System.out.println("Father's name = "+obj.fname + " \nSon's name = " + obj.sname); } } |
Output
1 2 3 4 5 6 |
This is the parent class This is the child class Father's name = Ramesh Son's name = Sachin |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
No Comments