Inheritance is a mechanism wherein a new class is derived from an existing class. In Java, classes may inherit or acquire the properties and methods of other classes. A class derived from another class is called a subclass, whereas the class from which a subclass is derived is called a superclass. The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of “extends” is to increase functionality. Types of inheritance in java Note- Private members and constructors of a base class are never inherited.
Single Inheritance Example
class Ram{ void wise() { System.out.println(“this is super class”); } } class Kush extends Ram{ void brave(){ System.out.println(“this is child class “); } } public class I1{ public static void main(String args[]){ Kush m =new Kush (); m. brave (); m.wise(); }}
Multilevel Inheritance
class A1{ void work() { System.out.println(“working…”); } } class B1 extends A1{ void play() { System.out.println(“playing…”); } } class C1 extends B1{ void show() { System.out.println(“showing.”); } } public class I2{ public static void main(String args[]){ C1 c=new C1(); c.work(); c.play();
c.show(); }}
Hierarchical Inheritance
class Shiv{ void care() { System.out.println(“caring.”); } } class Ganesh extends Shiv{ void happy(){ System.out.println(“happyness…”); } } class Kartik extends Shiv{ void protect() { System.out.println(“protecting…”); } } public class I3{ public static void main(String args[]){ Kartik k=new Kartik(); Ganesh g=new Ganesh(); k.protect(); g.happy(); }}