Ad

Inheritance

 Inheritance

What is inheritance:

Inheritance in Java is an instrument where one item obtains all the properties and practices of a parent object. It is a significant piece of OOPs (Object Oriented programming framework). 

The thought behind legacy in Java is that you can make new classes that are based after existing classes. At the point when you acquire from a current class, you can reuse techniques and fields of the parent class. Besides, you can include new techniques and fields in your present class too. 

Inheritance speaks to the IS-A relationship which is otherwise called a parent-kid relationship.

Why use inheritance in java: 



  • For Method Overriding (so runtime polymorphism can be accomplished). 



  • For Code Reusability.

Example:


class Person
{
private String name;
private int age;
public void setName(String n)
{
name = n;
}
public String getName()
{
return(name);
}
public void setAge(int a)
{
age = a;

}
public int getAge()
{
return(age);
}
}
class Student extends Person
{
private int roll;
public void setRoll(int r)
{
roll = r;
}
public int getRoll()
{
return(roll);
}
}
public class Inheritance
{
public static void main(String args[])
{
Student s = new Student();
s.setName("Usman");
s.setAge(19);
s.setRoll(46);

System.out.println("Name ="+s.getName() );
System.out.println("Age ="+s.getAge() );
System.out.println("Roll No ="+s.getRoll() );
}

}

Post a Comment

0 Comments