Java program to create an object of a class as a data member in another class

Learn how to create an object of a class as a data member in another 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, In the Employee class, we will create an object of Person class as a data member.

Program/Source Code:

The source code to create an object of a class as a data member in another class is given below. The given program is compiled and executed successfully.

// Java program to create an object of a class 
// as a data member in another class

class Person {
  String name;
  int age;

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

class Employee {
  int emp_id;
  int emp_salary;
  Person P;

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

  void printEmployeeDetails() {
    System.out.println("Employee ID     :  " + emp_id);
    System.out.println("Employee Name   :  " + P.name);
    System.out.println("Employee Age    :  " + P.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 and create the reference of Person class in the Employee class, The Employee class has some additional data members, are emp_id, emp_salary. Here, we initialized the data members using constructors.

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 Class and Object Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.