Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Inheritance

Inheritance is one of the important feature of OOP.

Inheritance allows to create a new class from an existing class.

The new class what ever we will create, is known as sub class(child or derived class).

The existing class where the sub class is derived is known as super class(parent class).

We use extends keyword to create sub class and perform inheritance in JAVA.

Inheritance provides the concept of re-usability which is the main advantage.

In JAVA, inheritance is an is-a relationship. That means we use inheritance if there exists an is-a relationship between two classes. For example;
Dog is an animal
Apple is a fruit
Here Dog is inheriting from Animal and Apple is inheriting from Fruit.


Example1:

InheritanceExample1.java

package com.inheritance;
class Demo1 //Demo1 : super class
{
	void m1()
	{
		System.out.println("JAVA Programming");
	}
}
class Demo2 extends Demo1 //Demo2 : Sub class
{
	void m2()
	{
		System.out.println("JAVA Inheritance");
	}
}
public class InheritanceExample1
{
	public static void main(String[] args)
	{
		Demo2 obj=new Demo2();
		obj.m1();
		obj.m2();
	}
}

Output
JAVA Programming
JAVA Inheritance


Note: The sub class object can access super class property.


Example2:

InheritanceExample2.java

package com.inheritance;
class A11 //A11 : super class
{
	int x;
}
class A22 extends A11 //A22 : sub class
{
	int y;
	void get()
	{
		x=100;
		y=200;
	}
	void show()
	{
		System.out.println("x="+x);
		System.out.println("y="+y);
	}
}
public class InheritanceExample2 {
	public static void main(String[] args) {
		A22 ob = new A22();
		ob.get();
		ob.show();
	}
}

Output:

x=100
y=200
Note: The sub class property can access super class property.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext