Java Program to Create an Object of a Class as a Data Member in Another Class

You are currently viewing Java Program to Create an Object of a Class as a Data Member in Another Class

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

// 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

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply