The
keyword used for inheritance is extends.
Syntax:
|
super : reference variable that is used to refer parent class
objects.
In
the example given below the Base Class is Employee
and the Derived Class is Manager :
public
class Employee {
int
empid;
String
empname;
double
salary;
public
Employee() {
System.out.println("Default
constructor of Emp class");
empid
= 1;
empname
= "Ram";
salary
= 10000;
}
public
Employee(int empid, String empname, double salary) {
System.out.println("Parameterized
constructor of Emp class");
this.empid
= empid;
this.empname
= empname;
this.salary
= salary;
}
@Override
public
String toString() {
return
empid + " " + empname + " " + salary;
}
public double calSalary() {
return
salary;
}
protected
String showName(){
return
empname;
}
}
public class Manager extends Employee {
int
ptallow, fdallow, incentive;
public
Manager(int empid, String empname, double salary, int ptallow, int fdallow, int
incentive) {
super(empid,
empname, salary);
System.out.println("Parameterized
constructor of Manager class");
this.fdallow
= fdallow;
this.ptallow
= ptallow;
this.incentive
= incentive;
}
@Override
public
String toString() {
return
empid + " " + empname + " " + salary + " " + ptallow
+ " " + fdallow + " " + incentive;
}
@Override
public
double calSalary() {
//
TODO Auto-generated method stub
return
super.calSalary() + ptallow + fdallow;
}
}
//Driver
code
public
class TestMain {
public
static void main(String[] args) {
Employee e1 = new
Empoyee(100,"Smruti",10000);
//object of Employee
Manager
m1 = new Manager(101,"Swapna",25000,100,100,100); //object of Manager
System.out.println(e1.showName());
System.out.println(e1.calSalary());
System.out.println(m1.showName());
System.out.println(m1.calSalary());
}
}
Output:
Smruti
10000
Swapna
25200
Smruti
Khire
K38
Soo helpful! This is what motivated me to study during quarantine!!
ReplyDeleteThat's great!Happy Coding!!
DeleteIts quarantine time stay safe and sleep๐
ReplyDelete๐๐
ReplyDelete