0% found this document useful (0 votes)
45 views31 pages

Topic 4 - Classes (Intermediate) (Part 2)

This document discusses arrays of objects in object-oriented programming. It explains that arrays can store references to objects rather than the objects themselves. An array of objects is declared with a class name and size, and objects are instantiated and stored in the array using indexes. Attributes of a class can also be arrays, allowing multiple values to be stored for each object. Composite objects are discussed as a way to combine simple objects into more complex ones, with an example of parts like wheels and engine composing an automobile object. Examples are provided of creating and using arrays of objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views31 pages

Topic 4 - Classes (Intermediate) (Part 2)

This document discusses arrays of objects in object-oriented programming. It explains that arrays can store references to objects rather than the objects themselves. An array of objects is declared with a class name and size, and objects are instantiated and stored in the array using indexes. Attributes of a class can also be arrays, allowing multiple values to be stored for each object. Composite objects are discussed as a way to combine simple objects into more complex ones, with an example of parts like wheels and engine composing an automobile object. Examples are provided of creating and using arrays of objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

TOPIC 4: CLASSES – INTERMEDIATE (PART 2)

CSC 435 OBJECT ORIENTED PROGRAMMING


CHAPTER OUTLINE

 ARRAY OF OBJECTS
 COMPOSITE OBJECTS
 APPLICATION – SIMPLE SORTING AND SEARCHING ALGORITHM
ARRAYS

Primitive Data-type Object


Bicycle bike [ ];
double rainfall []; bike = new Bicycle[10];
rainfall = new double[12]; ..
bike [i] = new Bicycle( );

Bicycle[ ] bike = new Bicycle[10];


double[] rainfall = new double [12]; ..
bike [i] = new Bicycle();
ARRAY OF PRIMITIVE DATA TYPE

• An array is a collection of similar data types.


• Array is a container object that hold values of homogenous type.
• It is also known as static data structure because size of an array must be specified at the time
of its declaration.
• Array declaration:
➢ data_type variable [ ] = new data_type[size];
➢ Example: int num [ ] = new int[10];
➢ This example creates an array of type int with space for 10 int variables inside.

• new operator is used to initialize the memory of an array.


ARRAY OF PRIMITIVE DATA TYPE

Primitive data Array declaration


type
int int num [ ] = new int [5];
double double num [ ] = new double [5];
char char grade [ ] = new char [5];

//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

 Create array to store references to objects


 The array does not store the object, only
store reference/address
 The variable that store array itself is also a
reference variable
ARRAY OF OBJECTS

❖ To declare the array of object:

className[] arrayName= new className[size]

❖ For example, we have class Student and want to create an array named s that will
store 100 objects

Student[] s = new Student[100]


ARRAY OF 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:

for (int index=0; index<array_name.length; index++)


array_name[index] = new class_name();

Where i is the index value


CREATING AN OBJECT ARRAY - 1
Only the name person is
Code A Person[ ] person; declared, no array is
allocated yet.
person = new Person[20];

person[0] = new Person( );

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;

DEFINITION private double [ ] test = new double [2];

public Student()
{
Example : name=" ";

Each student has two attributes which are //array initialization


name and test. Two marks of test 1 and test 2 test = new double[ ]{0.0 , 0.0};
will be stored. }

public Student (String n, double [ ] t)


Based on the problem above, {
Object is Student.
name =n;
Attributes :
String name for(int i=0; i< test.length; i++)
double [ ] test = new double [2] {
test[i] = t[i];
}
}
public void setStudent (String n, double [ ] t)
{ name =n;
for(int i=0; i< test.length; i++)
ATTRIBUTE
{ AS ARRAY IN CLASS DEFINITION
test[i] = t[i];
}
}
public String getName( ) {return name;}
public double [ ] getTest( ) {return test;}
public String toString()
{
String display =“ ";
for(int i=0; i< test.length; i++)
{
display = display + "\nTest"+(i+1)+ ": "+test[i];
}
return "Name is "+ name + "\nTest Marks are : " + display;
}
}
public static void main (String args[])
{
String name;
double [ ] test = new double[2];
Scanner sc = new Scanner (System.in);
System.out.println("Enter name: ");
name = sc.nextLine();

System.out.println("\n\n<<Full Mark is 100>>");


for(int j=0; j<test.length; j++)
{
System.out.println("Enter Test: " + (j+1));
test[j] = input.nextDouble();
}
Student2 s = new Student2( );
s.setStudent2(name, test);
System.out.println("All information");
System.out.println(s.toString());
System.out.println("***************\n");
}
OUTPUT OF ATTRIBUTE AS ARRAY
public static void main (String args[ ])
{
String name;
double [ ] test = new double[2];
Student s [ ] = new Student [2];

Scanner input = new Scanner (System.in);


for(int i =0; i<s.length; i++)
{
System.out.println("******* Student "+(i+1)+" *******");
System.out.println("Enter name");
name = input.nextLine();
System.out.println("\n<<Full Mark is 100>>");

for(int j=0; j<test.length; j++)


{
System.out.println("Enter Test " + (j+1));
test[j] = input.nextDouble();
}
s [i] = new Student();
s [i].setStudent(name, test);
}
ARRAY IN ATTRIBUTES AND OBJECT

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

❖ Another way to relate two classes.


❖ Are often referred to as having a "has a" relationship
❖ Example: every person has a date of birth.
❖ Object composition is a way to combine simple objects or data types into more
complex ones.
❖ A real-world example of composition may be seen in an automobile: the objects
wheel, steering wheel, seat, gearbox and engine may have no functionality by
themselves, but an object called automobile containing all of those objects would
serve a higher function
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

❖ The most common operation that we use on array of objects is


searching.
❖ We can search for:
❑ Object with highest/lowest value for any attribute/data
members.
❑ Object with specific value for any attribute/data members.
APPLICATION – EXAMPLE (CLASS STUDENT)
APPLICATION – EXAMPLE (MAIN PROGRAM)
APPLICATION – EXAMPLE (FINDING STUDENT WITH HIGHEST
SCORE)

• You can search student with


minimum score just by switching
‘>’ with ‘<‘ inside if
APPLICATION – EXAMPLE (FINDING STUDENT WITH SPECIFIC
NAME)
PERSON ARRAY PROCESSING – SAMPLE 1
String name, inpStr;
int age;
char gender; Create Person objects and
int size = 30; //size can request from user set up the person array
Person person [] = new Person [size];

for (int i = 0; i < person.length; i++)


{
System.out.println(“Enter a name: “); //read in data values
name = sc.nextLine();
System.out.println(“Enter an age: “);
age = sc.nextInt();
System.out.println(“Enter a gender: “);
gender = sc.next().charAt(0);

person [i] = new Person( );

person [i].setName (name);


person [i].setAge (age);
person [i].setGender(gender);
}
PERSON ARRAY PROCESSING – SAMPLE 2

int minIdx = 0; //index to the youngest person Find the youngest


int maxIdx = 0; //index to the oldest person and oldest person

for (int i = 1; i < person.length; i++) {

if ( person[i].getAge() < person[minIdx].getAge() ) {


minIdx = i; //found a younger person

} else if ( person[i].getAge() > person[maxIdx].getAge() ) {

maxIdx = i; //found an older person


}
}

//person[minIdx] is the youngest and person[maxIdx] is the oldest


PERSON ARRAY PROCESSING – SAMPLE 3
boolean found = false; Searching for
int loc=0; particular person
for (int i = 0; i < person.length; i++)
{ if(person[i].getName().equalsIgnorecase("Latte") )
{ found = true;
loc =i;
}
}
if ( found == true)
{ //found - successful search
System.out.println("Found Ms. Latte at position " + loc);}
else {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");
}

You might also like