Java Program to Implement Single Inheritance
Java Single Inheritance:
In the example below Employee is superclass and Manager is subclass. We can use the concept of inheritance in java using
Single Level Inheritance in Java
In single level inheritance one class is derived using only one class. Means a derived subclass has only one superclass. For example if a class B is derived from some class A then A is called Superclass and B is called subclass.In the example below Employee is superclass and Manager is subclass. We can use the concept of inheritance in java using
extends
keyword.
Java Program For Single Inheritance
import java.io.*;
class Employee
{
private static int id = 0;
private String name;
private String department;
private float salary;
float sal;
Employee()
{
id = ++id;
}
// no need for parametized constructor as there is accept() method
void accept() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n ****Enter Employee Details****");
System.out.print("\n Enter Name: ");
name = br.readLine();
System.out.print(" Enter Department: ");
department = br.readLine();
System.out.print(" Enter Salary: ");
salary = Float.parseFloat(br.readLine());
sal = salary;
}
void display()
{
System.out.println(" Id: " + id);
System.out.println(" Name: " + name);
System.out.println(" Department: " + department);
System.out.println(" Salary: " + id);
}
}
class Manager extends Employee
{
private float bonus;
float bon;
void accept() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
super.accept();
System.out.print(" Enter Bonus: ");
bonus = Float.parseFloat(br.readLine());
bon = bonus;
}
void display()
{
super.display();
System.out.print(" Bonus: " + bonus);
}
}
public class SingleInheritanceJava
{
public static void main(String[] args) throws IOException
{
int i, size;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many records do you want to create:- ");
size = Integer.parseInt(br.readLine());
float[] totalSal = new float[size];
Manager[] ma = new Manager[size];
for(i=0;i<size;i++)
{
ma[i] = new Manager();
ma[i].accept();
totalSal[i] = ma[i].sal + ma[i].bon;
}
float max = 0; int index = 0;
for(i=0;i<size;i++)
{
if(max < totalSal[i])
{
max = totalSal[i];
index = i;
}
}
System.out.println("\n ****Employee Having Maximum Salary**** \n");
ma[index].display();
}
}
/* Output of above code:
How many records do you want to create:- 2
****Enter Employee Details****
Enter Name: Shubham
Enter Department: Computer
Enter Salary: 1000.01
Enter Bonus: 100
****Enter Employee Details****
Enter Name: Chinmay
Enter Department: Gym
Enter Salary: 10000.12
Enter Bonus: 1000
****Employee Having Maximum Salary****
Id: 2
Name: Chinmay
Department: Gym
Salary: 2
Bonus: 1000.0
*/