Inheritance in Java Programming

Inheritance in Java Programming

Previous Home Next

 

Inheritance:- is the ability of objects in java to inherit properties and methods from other objects. 

When an object inherits from another object it can add its own 
properties and methods. The object that is being inherited from is 
called the parent or base class and the class that is inheriting from 
the parent is called the child or derived class.

Types of inheritance:

Single inheritance :-When a  subclass is derived simply from it's parent class then this mechanism is known as simple inheritance.


Multilevel inheritance:- When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance
 


 
class Person
{
private String name;

public void setName(String n)
{
name = n;
}

public String getName()
{
return name;
}
}
class Student extends Person
{
private String stuId;

public void setStuId(String sn)
{
stuNum = sn;
}

public String getStuId()
{
return stuId;
}
}
public class TInheritance
{
public static void main(String[] args)
{
Student stu = new Student();
stu.setName("Nancy John");
stu.setStuId("12345");
System.out.println("Student Name: " + stu.getName());
System.out.println("Student Number: " + stu.getStuId());
}
}


Previous Home Next