JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Saturday 8 November 2014

Inheritance


Inheritance is used for reuse the code,Programming work can be efficient by saving the time without writing the code again.Programmer can use the code of parent class in the child class.So we can use the features of parent class to child class,child class gets all the feature of parent class by using extends keyword.Here in example we use the  mutator set() and accesor get()  method to set and get the values.Child class Trainee will acquire all the feature of Parent class Trainer and apart from this we will use another variable Grade for student which is required and was not in parent class Trainer.Now we can get the result by setting the values with the help of  child class object.
Example:

class Trainer
{
int id;
String name;
int age;
String address;

void setId(int id) //Mutator method
{
this.id=id;
}
int getId()   //Accesor method
{
return id;
}

void setName(String name) //Mutator method
{
this.name=name;
}
String getName() //Accesor method
{
return name;
}

void setAge(int age)
{
this.age=age;
}
int getAge()
{
return age;
}

void setAddress(String address)
{
this.address=address;
}
String getAddress()
{
return address;
}
}

class Trainee extends Trainer
{
char grade;
void setGrade(char grade)
{
this.grade=grade;
}
char getGrade()
{
return grade;
}
}

class InheritanceDemo
{
public static void main(String args[])
{
Trainee tr=new Trainee();
tr.setId(1);
tr.setName("Rupak");
tr.setAge(25);
tr.setAddress("Bandra,Mumbai,MH");
tr.setGrade('A');

System.out.println("Id is : "+tr.getId());
System.out.println("Name is : "+tr.getName());
System.out.println("Age is : "+tr.getAge());
System.out.println("Address is : "+tr.getAddress());
System.out.println("Grade is : "+tr.getGrade());
}
}
O/P:
Id is : 1
Name is : Rupak
Age is : 25
Address is : Bandra,Mumbai,MH
Grade is : A

No comments:

Post a Comment

Designed By Blogger Templates