Composition
Wednesday, 16 October 2024 13:08
What is composition?
Composition is having an object of another class inside one class.
The object is often a class variable and has to be initialised in the constructor.
Students
• name : String
• grade : int
Subjects
• subjectName : String
• student : Student
Q2:
public class Students
{
private String name;
private int grade;
public Students(String n, int g)
{
name = n;
grade = g;
}
@Override
public String toString()
{
return name + "\t" + grade;
}
}
Q3:
• create the class variables
• initialise the class variables within the constructor
• toString: display the Students Class toString first, followed up by the subject name
(tabbed)
public class Subjects
{
private String subjectName;
private Students student; <- this is an object as its data type is of a class's
//It is an object of the Students class because it is of the Students class data type
public Subjects(String sn, Students s)
{
subjectName = sn;
student = s;
}
@Override
public String toString()
{
return [Link]() + "\t" + subjectName;
}
//Methods from the class can be accessed by using the object for calling the specific
method.
}
Text File: [Link]
Shriyan Naidoo#12
Information Technology
Yashika Govender#12
Mathematics
Sayuv Singh#12
Afrikaans
Q4
4.1 Create the SubjectsManager class
4.2 Create an array to hold 50 subjects manager objects and a counter, size to keep track
of the number of objects. These variables must not be accessible outside of the
SubjectManager class.
4.3 Read from textfile, initialise each object in the array.
4.4 Create a toString method to display all students data, one below the other on a new line.
public class SubjectsManager
{
private Subjects sArr[] = new Subjects[50];
private int size = 0;
public SubjectsManager()
{
try
{
Scanner sc = new Scanner(new FileReader("[Link]"));
while ([Link]())
{
String line = [Link]();
Scanner scLine = new Scanner(line).useDelimiter("#");
String n = [Link]();
int g = [Link]();
String sn = [Link]();
//Create a Students object-we have to initialise a students object because it is
a variable in the Subjects class
Students s = new Students(n, g); <- ensure that it matches the parameters in the
constructor
//initialise the array:
sArr[size] = new Subjects(sn, s);
size++;
}
[Link]();
}
catch (Exception e)
{
[Link]([Link]());
}
}
public String toString()
{
String display = "";
for (int i = 0; i < size; i++)
{
display += sArr[i].toString() + "\n";
}
return display;
}
}
Q5
• UI Class
• Create an Object of the Manager Class
• Output/Print your toString from there by calling it
public class SubjectsUI
{
public static void main(String[] args)
{
SubjectsManager sm = new SubjectsManager();
[Link]([Link]());
}
}