‹‹ Previous
Next ››
Java Inheritance
- Inheritance is used to extend the features of a class.
- It uses the keyword 'extends' for inheritance.
- It creates parent-child relationship among classes.
- Parent class is also called super class.
- Child class is also called sub class.
- Child class uses the keyword 'extends' for extending the features of parent class.
- Java does not permit multiple inheritance.
Example
class Student {
int rollno;
String name;
void setdata(int rl, String nm)
{
rollno = rl;
name = nm;
}
void getdata()
{
System.out.println("Roll no is " + rollno);
System.out.println ("Name is " + name);
}
}
class job extends Student {
String jobname;
void setdata (int r, String m, String jb)
{
rollno = r;
name = m;
jobname = jb;
}
void getdata()
{
System.out.println(" Roll no " + rollno);
System.out.println ("Name is " + name);
System.out.println ("Job name is " + jobname);
}
}
class demoinheritance {
public static void main (String args[] )
{
job obj1 = new job();
obj1.setdata(123,"Ashish", "Project Manager");
obj1.getdata();
}
}
Explanation of the program
- The program creates a class named Student . It has two variables and two methods.
- The class job inherits (or extends) the features of the class Student .
- The class job inherits two variables from the class Student and add one more variable jobname .
- Similarly, class job inherits both methods setdata() and getdata() .
- Class job extends both methods setdata() and getdata() to make them for three variables.
- Class demoinheritance creates an object named obj1 of class job in the main() function.
- Object obj1 calls setdata() and getdata() methods of class job .
- Methods setdata() and getdata() of class job are enhanced version than same methods in parent class Student .
Output of the program
Roll no 123
Name is Ashish
Job name is Project Manager
‹‹ Previous
Next ››