Topic 4 - Classes (Intermediate) (Part 2)
Topic 4 - Classes (Intermediate) (Part 2)
ARRAY OF OBJECTS
COMPOSITE OBJECTS
APPLICATION – SIMPLE SORTING AND SEARCHING ALGORITHM
ARRAYS
//array creation
int num [ ]=new int[5];
//array initialization
num = new int[ ]{2,3,4,5,6};
import java.util.*;
ARRAY OF PRIMITIVE public class arrayIntDataType
{
DATA TYPE public static void main(String [ ] args)
{
int num [ ]= new int[3];
Example program array of int data type
Scanner sc= new Scanner(System.in);
for(int i=0;i<3;i++)
{
System.out.print("Enter a number: ");
num[i]=sc.nextInt();
for(int i=0;i<3;i++)
{
System.out.println("Number"+(i+1)+
":"+num[i]);
}
}
}
ARRAY OF OBJECTS
❖ For example, we have class Student and want to create an array named s that will
store 100 objects
❖ After the array has been created, by default all index will store null value (no
references/address to object)
❖ To instantiate object, syntax is as follow:
person
State
of
Memory
After A is executed
CREATING AN OBJECT ARRAY - 2
Now the array for storing
Code Person[ ] person;
20 Person objects is
B person = new Person[20]; created, but the Person
objects themselves are
person[0] = new Person( );
not yet created.
person
person
0 1 2 3 4 16 17 18 19
State
of
Memory
After B is executed
CREATING AN OBJECT ARRAY - 3
One Person object is
Person[ ] person; created and the reference
Code to this object is placed in
person = new Person[20]; position 0.
C person[0] = new Person( );
person
0 1 2 3 4 16 17 18 19
State
of Person
Memory
After C is executed
public class Student
{
ATTRIBUTE AS ARRAY IN CLASS private String name;
public Student()
{
Example : name=" ";
System.out.println("*********All information***********");
for(int h=0; h<s.length; h++)
{
System.out.println("Student "+(h+1)+":\n"+ s[h].toString( ) +"\n");
}
System.out.println("********************** **********\n");
}
ARRAY OF OBJECTS - EXAMPLE
COMPOSITE OBJECTS
❖ For example, a university owns various departments (e.g., chemistry), and each
department has a number of professors.
❖ If the university closes, the departments will no longer exist, but the professors
in those departments will continue to exist.
❖ Therefore, a University can be seen as a composition of departments, whereas
departments have an aggregation of professors. In addition, a Professor could
work in more than one department, but a department could not be part of
more than one university.
COMPOSITE OBJECTS - EXAMPLE
APPLICATION – SIMPLE SORTING AND SEARCHING ALGORITHM