MainMenu

Home Core Java Overview Maven Tutorials

Sunday, 15 January 2017

Inheritance in java with example



Inheritance in java with example

For Video : CLICK HERE



As like Overloading, Inheritance is also a OOPs feature, Inheritance provide a mechanism that allow a class to inherit property of another class.



When a class inherit another class using extends keywords then all non-private members including fields and Methods.
In java inheritance cab be described in parent, child relationship also known as Super Class(Parent) and Sub class(child) in java language.

Syntax:
Class Parent
{
..............
}
Class Child extends Parent
{
...............
}
Example : In below example parent class has a method witch will be inherited by child and then object of class child will access the methods
package chandan_test1;
class C_parent
{
int x;
public void sum(int a, int b)
{
x = a+b;
System.out.println("Your sum is :" +x);
}
}
public class C_inhritance extends C_parent
{
public void sub(int c, int d)
{
x = d-c;
System.out.println("Your Difference is :" +x);
}
public static void main(String args[])
{
int a = 10;
int b = 20;
C_inhritance alpha = new C_inhritance();
alpha.sum(a,b);
alpha.sub(a,b);
}
}
Output:
Your sum is : 30
Your Difference is : 10

Tags :What is inheritance in Java?,java inheritance with example



No comments:

Post a Comment