Q:

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

belongs to collection: Java Class and Object Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to demonstrate the instanceof operato... >>
<< Java program to create an object of a class as a d...