ADVERTISEMENT
ADVERTISEMENT

Java program to create an employee class by inheriting Person class

Learn how to create an employee class by inheriting Person class in Java?
Submitted by Nidhi, on March 24, 2022

Problem Solution:

In this program, we will create a Person class and then create a new class Employee by inheriting the features of the Person class using the "extends" keyword.

Program/Source Code:

The source code to create an employee class by inheriting the Person class is given below. The given program is compiled and executed successfully.

// Java program to create an employee class 
// by inheriting Person class

class Person {
  String name;
  int age;

  Person(int age, String name) {
    this.name = name;
    this.age = age;
  }
}

class Employee extends Person {
  int emp_id;
  int emp_salary;

  Employee(int id, String name, int age, int salary) {
    super(age, name);
    emp_id = id;
    emp_salary = salary;
  }

  void printEmployeeDetails() {
    System.out.println("Employee ID     :  " + emp_id);
    System.out.println("Employee Name   :  " + name);
    System.out.println("Employee Age    :  " + age);
    System.out.println("Employee Salary :  " + emp_salary);
  }
}

public class Main {
  public static void main(String[] args) {
    Employee emp = new Employee(101, "Savas Akhtan", 32, 22340);
    emp.printEmployeeDetails();
  }
}

Output:

Employee ID     :  101
Employee Name   :  Savas Akhtan
Employee Age    :  32
Employee Salary :  22340

Explanation:

In the above program, we created 3 classes Person, Employee, and Main. The Person class contains two data members' name and age. Then we created the Employee class by inheriting the Person class, The Employee class has some additional data members, are emp_id, emp_salary. Here, we initialized the data members using constructors, Employee class constructor calls Person class constructor using super keyword.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the object of the Employee class and printed the employee details.

Java Inheritance Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.