Task 5: Composition

A class can have references to objects of other classes as members, this is called composition. For example Car is composed of Engine and Wheels objects. Rectangle is composed of or "has" width and height. User class has name, Address and age attributes, etc. Composition is sometimes also referred as "has-a" relation because we can make statement like "Student has-a name", "Rectangle has-a length", "Car has-a Engine" etc. Below task is to make sure you well understand how to use other types as attributes or fields in our classes. How to initialize these attributes, how to change and read the values of each attribute.

For each class/attributes described below, choose appropriate data type. All attributes of each class should be private and exposed via get/set methods. Also define at least one constructor that allows to initialize 2-3 attributes of object.

  1. Define a class Course with courseCode and courseTitle attributes.
  2. Define a class PhoneNumber with countryCode, cityCode and lineNumber attributes.
  3. Define a class Address with streetAddress, town, city, country and phoneNumber attributes. Attribute phoneNumber shall be of type PhoneNumber.
  4. Define a class Student with name, email, cnic, course1, course2 and address attributes. Where course1 and course2 should be of type Course and address shall be of type Address. Define a constructor in Student class that takes cnic, name and address only.

Create a StudentTest class, in its main method, create a Student object named student1. Fully initialize its all attributes. cnic, name and address shall be initialized by constructor. Other attributes should be initialized using setter methods. All attribute values should be given by user. After the object is fully initialized, print all attribute values using get methods.

Make another object student2, assume who also live at same address as student1. Reuse the address object of student1 to initialze student2 address. You don't need to take attributes from user input for student2 object.


  1. Sir can you please post a demo code..?


Post a Comment