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


This program creates a Student object that contains a Person object as one of its member variables. The Person object represents the personal details of the student, such as their name and age.

The Student class has a constructor that initializes the Person object and sets the student ID. The printEmployeeDetails method prints the details of the Student object, including the ID, name, and age.

Overall, this program demonstrates how to create an object that contains another object as one of its member variables.

Source Code

public class Create_Object
{
  public static void main(String[] args) 
  {
    Student emp = new Student(101, "Joes", 32);
    emp.printEmployeeDetails();
  }
}
class Person
{
  String name;
  int age;
 
  Person(int age, String name)
  {
    this.name = name;
    this.age = age;
  }
}
 
class Student
{
  int stu_id;
  int stu_per;
  Person P;
 
  Student(int id, String name, int age)
  {
    P = new Person(age, name);
    stu_id = id;
  }
 
  void printEmployeeDetails()
  {
    System.out.println("Student ID     :  " + stu_id);
    System.out.println("Student Name   :  " + P.name);
    System.out.println("Student Age    :  " + P.age);
  }
}

Output

Student ID     :  101
Student Name   :  Joes
Student Age    :  32