That is to say, the idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. So the key word here is "reuse code", doesn't sound like a good idea?
Imagine you are sitting at work and get a call your rich uncle died leaving you 1 Billion dollars. What is the first thing you do? Probably SPEND THE MONEY!! HOORAY!!!!...well, with Inheritance, is something similar, but in this case your uncle didn't die but is letting you use his money (methods and fields)
Output
Imagine you are sitting at work and get a call your rich uncle died leaving you 1 Billion dollars. What is the first thing you do? Probably SPEND THE MONEY!! HOORAY!!!!...well, with Inheritance, is something similar, but in this case your uncle didn't die but is letting you use his money (methods and fields)
Definitely Inheritance is super useful from a developer perspective, think about it:
- Reusability -- facility to use public methods of base class without rewriting the same
- Extensibility -- extending the base class logic as per business logic of the derived class
- Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class
- Overriding--With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.
class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //method of Child class cobj.p1(); //method of Parent class } }
Output
Child method Parent method
No comments:
Post a Comment