0% found this document useful (0 votes)
2 views59 pages

Chapter 4 - Classes Intermediate

This chapter covers intermediate concepts in object-oriented programming, focusing on method overloading, passing objects as parameters, and using objects as method types. It explains the rules for method overloading, provides examples, and discusses the implications of modifying objects when passed as parameters. Additionally, it introduces arrays of objects and demonstrates how to manipulate them through various examples.

Uploaded by

2024806856
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views59 pages

Chapter 4 - Classes Intermediate

This chapter covers intermediate concepts in object-oriented programming, focusing on method overloading, passing objects as parameters, and using objects as method types. It explains the rules for method overloading, provides examples, and discusses the implications of modifying objects when passed as parameters. Additionally, it introduces arrays of objects and demonstrates how to manipulate them through various examples.

Uploaded by

2024806856
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

CHAPTER 4

Classes –
Intermediate

By
En. Mohd Nizam bin Osman
(Senior Lecturer)
Department of Computer Science
Faculty of Computer and Mathematical Science, UiTM
Perlis
Objectives
• By the end of this chapter, students should be able to:

Discuss issues related to the design of methods with object


as parameter and object as method type.

Understand the concept of decomposition and method


overloading.

Write and use method overloading.

Write and use an array of object.


2
Method Overloading
(Characteristics)

All the methods MUST have the same


name.

METHOD
OVERLOADING

All the methods MUST have different


formal parameter list.
Method Overloading

• Example:
Method Overloading
public void methodA (int x)

public void methodA (int x, double y)

public void methodA (double y, int x)

public void methodA (char ch, int x, double y)

public void methodA (char ch, int x, String name)

a va ? According to the number of parameters and type


J sh
w i of the parameter
Ho ingu
i st Example: methodA(10);
d
methodA(10, 20.5);
methodA(‘A’, 10, “Ali”);
Method Overloading
• When you give two or more methods the same
name within the same class, you are
overloading the method name- called (method
overloading).

• To do this, you must ensure that the different


method definitions have something different
about their parameter lists (arguments).
Method Overloading

• Example: WRONG method overloading:


Method Overloading
public void methodA (int x, double y, char ch)
public void methodA (int a, double b, char xx )

×because both have three parameters


and the data type of the corresponding
parameter is the same.
Method Overloading
(Rules – Different Parameter)
• Two methods are said to have different formal
parameter list if both method have:

Rule Rule Rule


A different
1 2 A different 3 order of the
A different set of the formal
number of data type of parameter,
formal the formal must differ in
parameters. parameters. at least one
position.
Method Overloading
(Rules – Different Parameter)
• Example:
public void methodA();
Method Overloading Description
public void methodA (int x) RULE 1
public void methodA (char ch) RULE 2
public void methodA (int x, double y) RULE 1
public void methodA (double y, int x) RULE 3
public void methodA (char ch, int x, double y) RULE 1
public void methodA (char ch, int x, String name) RULE 2
public void methodA (int x, char ch, String name) RULE 3
Method Overloading

CONCEPT:
Overloading a method name means
giving the same name to more than one
method within a class.
Method Overloading
(Example 1)
public class Overload
{
public static void main(String[] args)
{
double average1 = Overload.getAverage(40.0, 50.0);
double average2 = Overload.getAverage(1.0, 2.0, 3.0);
char average3 = Overload.getAverage('a', 'c');
System.out.println("average1 = " + average1);
System.out.println("average2 = " + average2);
System.out.println("average3 = " + average3);
} Method overloading
public static double getAverage(double first, double second)
{
return (first + second) / 2.0;
}

public static double getAverage(double first, double second, double


third)
{
return (first + second + third) / 3.0;
}
Method Overloading
(Example 1)
public static char getAverage(char first, char second)
{
return (char)(((int)first + (int)second) / 2);
}
} Method overloading

Sample Screen Output


average1 = 45.0
average2 = 2.0
average3 = b
Method Overloading
(Example 2)
public class MethodOverload
{
public static void main( String[] args )
{
System.out.printf( "Square of integer 7 is %d\n", square( 7 ) );
System.out.printf( "Square of double 7.5 is %f\n", square( 7.5 ) );
}

// square method with int argument


public static int square( int intValue )
{
System.out.printf( "\nCalled square with int argument: %d\n", intValue );
return intValue * intValue;
} Sample Screen Output
Called square with int argument: 7
// square method with double argument Square of integer 7 is 49
public static double square( double doubleValue ) Called square with double argument: 7.500000
{ Square of double 7.5 is 56.250000
System.out.printf( "\nCalled square with double argument: %f\n",
doubleValue );
return doubleValue * doubleValue;
}
} // end class MethodOverload
Object as Parameter
• When we pass an object as a parameter to a method,
the reference to the object is available to the method,
not a copy of the object itself.

• The value that is copied is the address of the actual


object.

• Therefore it is important to understand that when a


formal parameter object is used it modifies the actual
object state permanently.
Object as Parameter
(Example)
public class Circle {
pubic int radius;

public Circle(int r){


radius = r;
}
public void setRadius(int r){
radius = r;
}

public int getRadius(){


return radius;
}
//other methods
}
Object as Parameter
(Example)
public class ReferenceTest {
public static void main (String[] args)
{
Circle c1 = new Circle(20);
Circle c2 = new Circle(10);
Sample Screen Output
System.out.println ( “c1 Radius = “ + c1.getRadius());
System.out.println ( “c2 Radius = “ + c2.getRadius()); c1 Radius = 20.0
parameterTester(c1, c2); c2 Radius = 10.0
System.out.println ( “c1 Radius = “ + c1.getRadius()); circleA Radius = 15.0
System.out.println ( “c2 Radius = “ + c2.getRadius()); circleB Radius = 100.0
} c1 Radius = 15.0
c2 Radius = 10.0
public static void parameterTester(Circle circleA, Circle circleB)
{
circleA.setRadius(15);
circleB = new Circle(100);
System.out.println ( “circleA Radius = “ + circleA.getRadius());
System.out.println ( “circleB Radius = “ + circleB.getRadius());
}
}
Object as Parameter
(Example -Analysis)
STEP1 – Before calling parameterTester() STEP2 – parameterTester(c1, c2)

c1 c2 c1 c2

(20) (10) (10)


circleA circleB circleA (20) circleB
X X
STEP3 – circlA.setRadius(15) STEP4 – circlB = new Circle(100)
c1 c2
c1 c2

(15) (10)
(15) (10) circleA circleB
circleA circleB
16
(100)
Object as Parameter
(Example -Analysis)
STEP5 – After Returning from parameterTester(c1,c2)

c1 c2

(15) (10)
circleA circleB
X X
STEP 1
Sample Screen Output
c1 Radius = 20.0 STEP 3
c2 Radius = 10.0
STEP 4
circleA Radius = 15.0
circleB Radius = 100.0
c1 Radius = 15.0 STEP 5
c2 Radius = 10.0
17
Object as Parameter
(Example -Analysis)
• Therefore, programmers must be very careful
when using an object that has been passed as
a parameter, particularly when changes are
being made to objects of the same class.
Object as Method Type
• The classes that you create become data type.

• Same as the primitive data type declaration, it is


applicable to method members:

• Example:
public static Person findEldest(Person p1, Person p2)
{
//method body
}
Object as Method Type
(Example)
public class Person{
private String name;
private int age;

public Person(String nm, int ag)


{
name = nm;
age = ag;
}

public String getName()


{
return name;
}

public int getAge()


{
return age;
}
}
Object as Method Type
(Example)
public class AppPerson{
public static void main(String[] args)
{
Person p1 = new Person("Ali",120);
Person p2 = new Person("Abu",35);
Object as Person eldest = AppPerson.findEldest(p1,p2);
data type System.out.println("The eldest is: "
+eldest.getName());
}

public static Person findEldest(Person p1, Person p2)


{
if(p1.getAge() > p2.getAge())
Object as return p1;
else
method type return p2;
}
}
Array of Objects

RECAP Many objects ?


Variable for declaration
of objects Input first,
process later?
Repetition

• The variables for the object you have worked with so far
are designed to hold only one object at a time.

• Example:
Student stud = new Student();
Array of Objects
• Can solve using:
1. Using different variables to represent each object.
2. Repetition.

a l ?
• Example of using different variables:
a c tic
Student stud1 = new Student();
P r ?
i n g t ?
Student stud2 = new Student();
e a t j e c
Ch s ob
• Example of using repetition:
i o u
for (int i = 0; i<10; i++){
r e v
Student stud1 = new Student(); P
:
:
}
Array of Objects
• We can use arrays to manipulate objects.

• Example: Suppose that you have 100 of staffs.


Staff[] stf = new Staff[100]; stf
public class Staff {
private String name; stf[0]
private int staffNo;
private double salary;

public Staff () {
name = “”;
staffNo = 0;
stf[49]
salary = 0.0;
}
//other methods
}
stf[99]
Array of Objects
• Example: Suppose that you have 100 of staffs.
Staff[] stf = new Staff[100];

• We need to instantiate the staff object for each array


component.
for (int i = 0; i<100; i++)
stf[i] = new Staff();
Array of Objects
name “”

staffNo 0
stf
salary 0
stf[0]

name “”

stf[49] staffNo 0
salary 0

stf[99]
name “”

staffNo 0
salary 0
Array of Objects
(Example 1 – To Calculate Bonus based
on 60% of Salary)
import java.util.*;

public class Staff


{
private String name;
private int staffNo;
private double salary;

public Staff(){
name = "";
staffNo = 0;
salary = 0.0;
}

public Staff(String nm, int sn, double sal) {


name = nm;
staffNo = sn;
salary = sal;
}

public Staff(Staff newStaff) {


name = newStaff.name;
staffNo = newStaff.staffNo;
salary = newStaff.salary;
}
Array of Objects
(Example 1 – To Calculate Bonus based
on 60% of Salary)
public void setName(String nm){ name = nm; }
public void setStaffNo(int sn) { staffNo = sn; }
public void setSalary(double sal) { salary = sal; }

public String getName() { return name; }


public int getStaffNo() { return staffNo; }
public double getSalary() { return salary; }

public double calcBonus ()


{
double bonus = salary * 0.60;
return bonus;
}

public String toString()


{
return “\nName: " +name+ "\n" +"Staff Number: "+ staffNo+ "\n"
+"Salary: RM ”+ salary +"\n";
}
}
Array of Objects
(Example 1 – To Calculate Bonus based
on 60% of Salary)
public class StaffApp
{ Array declaration
public static void main(String[] args)
{
(STEP 1)
Scanner scan = new Scanner (System.in);
//declaration array of object
Staff[] stf = new Staff[10];

//instantiate array of object


for(int i=0; i<10; i++)
Instantiate the array
stf[i] = new Staff(); (STEP 2)
for(int i=0; i<10; i++)
{
System.out.print("Enter name: ");
String name = scan.nextLine();
System.out.print("Enter Staff Number: ");
int staffNo = scan.nextInt();
Input process
System.out.print("Enter Salary:"); (STEP 3)
double salary = scan.nextDouble();

stf[i].setName(name);
stf[i].setStaffNo(staffNo); Store the input onto the array
stf[i].setSalary(salary);
} using setter/mutator
(STEP 4)
Array of Objects
(Example 1 – To Calculate Bonus based
on 60% of Salary)
public class StaffApp
{ Array declaration
public static void main(String args[])
{
(STEP 1)
Scanner scan = new Scanner (System.in);
//declaration array of object
Staff[] stf = new Staff[10];

//instantiate array of object


for(int i=0; i<10; i++)
Instantiate the array
stf[i] = new Staff(); (STEP 2)
for(int i=0; i<10; i++)
{
System.out.print("Enter name: ");
String name = scan.nextLine();
System.out.print("Enter Staff Number: ");
int staffNo = scan.nextInt();
Input process
System.out.print("Enter Salary:"); (STEP 3)
double salary = scan.nextDouble();

stf[i] = new Staff(name, staffNo, salary); Store the input onto the array
}
using normal constructor
(STEP 4)
Array of Objects
(Example 1 – To Calculate Bonus based
on 60% of Salary)
//to find the maximum bonus
double maxBonus = stf[0].calcBonus();
Staff maxObject = stf[0];

for(int i=0; i<10; i++) Processing/Manipulate


{
if(stf[i].calcBonus() > maxBonus){ the methods & Data
maxBonus= stf[i].calcBonus(); (STEP 5)
maxObjek = stf[i];
}
}
//to display staff who get the maximum salary
System.out.println("Staff with maximum Bonus: "+"\n" +maxObject.toString()
+ “\nMaximum Bonus: RM”+maxBonus);

//to display all staff


for(int i=0; i<10; i++)
System.out.println("Staff " +i+"\n“ +stf[i].toString()
+ “\nBonus: RM”+stf[i].calcBonus());

}
}
Composite Objects
• In addition to a class containing data and
methods, it can also contain other classes.

• A class can have references to objects of other


classes as members. This is called
composition/nested class.

• Composition is another way to relate two


classes.
Composite Objects
• A nested class has access to the variables and methods of
the outer class, even if they are declared private.

• In certain situations this makes the implementation of the


classes easier because they can easily share information.

• Furthermore, the nested class can be protected by the


outer class from external use.

• This is a special relationship and should be used with care.


Composite Objects
(Example 1)
• In this example, we have three classes.
Date Employee
-month: int -firstName: String
-day: int -lastName: String DataType:
-year: int -birthDate: Date Data Object
-hireDate: Date
+Date(int, int, int)
+Employee(String, String,Date, Date)
+checkMonth(int): int
+displayInfo(): String
+checkDay(int): int
+displayInfo(): String

EmployeeTest
+main: (String[]): void
Composite Objects
(Example 1)

Employee Outter Class

Date

Inner Class
Composite Objects
(Example 1)
public class Date
{
private int month; // 1-12
private int day; // 1-31 based on month
private int year; // any year

// constructor: call checkMonth to confirm proper value for


// month; call checkDay to confirm proper value for day
public Date( int theMonth, int theDay, int theYear )
{
month = checkMonth( theMonth ); // validate month
year = theYear; // could validate year?
day = checkDay( theDay ); // validate day

System.out.printf("Date object constructor for date %s\n",


displayInfo() );
} // end Date constructor
Composite Objects
(Example 1)
// utility method to confirm proper month value
private int checkMonth( int testMonth )
{
if ( testMonth > 0 && testMonth <= 12 ) // validate month
return testMonth;
else // month is invalid
{
System.out.printf("Invalid month (%d) set to 1.",
testMonth );
return 1; // maintain object in consistent state
} // end else
} // end method checkMonth
Composite Objects
(Example 1)
// utility method to confirm proper day value based on month and year
private int checkDay( int testDay )
{
int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// check if day in range for month


if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
return testDay;

// check for leap year


if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;

System.out.printf( "Invalid day (%d) set to 1.", testDay );


return 1; // maintain object in consistent state
} // end method checkDay

// return a String of the form month/day/year


public String displayInfo()
{
return String.format( "%d/%d/%d", month, day, year );
} // end method toString
} //end of date class
Composite Objects
(Example 1)
public class Employee
{
private String firstName;
private String lastName;
private Date birthDate;
private Date hireDate;

// constructor to initialize name, birth date and hire date


public Employee( String first, String last, Date dateOfBirth, Date dateOfHire)
{
firstName = first;
lastName = last;
birthDate = dateOfBirth;
hireDate = dateOfHire;
} // end Employee constructor

// return string of Employee information


public String displayInfo()
{
return String.format( "%s, %s Hired: %s Birthday: %s", lastName,
firstName, hireDate.displayInfo(), birthDate.displayInfo() );
} // end method displayInfo
} // end class
Composite Objects
(Example 1)
public class EmployeeTest
{
public static void main( String[] args )
{
Date birth = new Date( 7, 24, 1949 );
Date hire = new Date( 3, 12, 1988 );
Employee employee = new Employee( "Bob", "Blue", birth, hire );
System.out.println( employee.displayInfo() );
} // end main
} // end class EmployeeTest

Sample Screen Output


Date object constructor for date 7/24/1949
Date object constructor for date 3/12/1988
Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949
Composite Objects
(Example 2)
To count the number of boxes that can be placed inside the container with
the size:- 3 meter width, 6 meter length, and 2 meter height. Then,
calculate the amount of the charge imposed for transportation cost (Assume
all boxes with the same size and measurement unit in (cm)). The following
table shows the charge for each box depends on the size:

Category size(cm3) charge

Small size < 1000 RM100/box

Medium 1001≤size<5000 RM150/box

Big size≥5000 RM200/box


Composite Objects
(Example 2)
• In this example we have three classes:
Box Container
-width: double Nested
-cntBox: int
-length: double -charge: double Object
-height: double -B: Box
-volume: double +countBox(double, double, double)
-category: char +toString(): String
+Box()
+Box(double, double, double)
+calcVolume(): void
+detCategory(): void
+getVolume():double
+getCategory() : char

CompositionApp
+main: (String): void
Composite Objects
(Example 2)
import java.util.*;
public class Box
{
private double width;
private double length;
private double height;
private double volume;
private char category;

public Box()
{
width = 0.0;
length = 0.0;
height = 0.0;
}

public Box(double wd, double lg, double hg)


{
width = wd;
length = lg;
height = hg;
}
Composite Objects
(Example 2)
public void calcVolume()
{
volume = width * length * height;
}

public void detCategory()


{
if (volume <= 1000)
category = ‘s';
else if (volume < 5000)
category = ‘m';
else
category = 'b';
}

public double getVolume()


{
return volume;
}

public double getCategory()


{
return category;
}
}//end class Box
Composite Objects
(Example 2)
public class Container
{
private int cntBox;
private double charge;
Box B; //composition or nested class

public void countBox(double wd, double lg, double hg)


{
B = new Box(wd, lg, hg);
B.calcVolume();
cntBox = (int)(36000000/B.getVolume());
}

public void calcCharge()


{
B.detCategory();
if(B.getCategory() == ‘s')
charge = cntBox * 100;
else if(B.getCategory() == ‘m')
charge = cntBox * 150;
else
charge = cntBox * 200;
}
Composite Objects
(Example 2)
public String toString()
{
String line1 ="The number of box: "+cntBox+"\n";
String line2 = "Charge for transportation cost: RM " +charge;
return line1 + line2;
}
}
Composite Objects
(Example 2)
public class CompositionApp
{
public static void main(String[] args)
{
Scanner scanner = new Scanner (System.in);

Container C = new Container();


System.out.print("Enter width for box: ");
double wd = scanner.nextDouble();
System.out.print("Enter length for box: ");
double lg= scanner.nextDouble();
System.out.print("Enter height for box: ");
double hg = scanner.nextDouble();

C.countBox(wd,lg,hg); Sample Screen Output


C.calcCharge(); Enter width for box:100.00
System.out.println(""+C.toString());
Enter length for box:100.00
Enter height for box:100.00
} The number of box:36
} Charge for transportation cost RM: 7200.00
Composite Objects
(Example 2)
• The proper way to communicate through
(CompositionApp class)
classes: main method

(Container Class)
Outer Class

(Box Class)

Inner Class
Application
(Sorting and Searching)
Application
(Sorting and Searching)
public class Person {
private int age;
private char gender;
String name;
public Person( ) {
}
public Person (int ag, char gen, String nm){
age = ag;
gender = gen;
name = nm;
}
public int getAge() {
return age;
}
public char getGender() {
return gender;
}
public String getName() {
return name;
}
//other methods
}
Application
(Sorting and Searching)
class AddressBook {
private Person[] entry;
private int count;
public AddressBook( ) {
}
public AddressBook(int size) {
count = 0;
if (size <= 0 ) { //invalid data value
throw new IllegalArgumentException("Size must be positive.");
}
entry = new Person[size];
for (int i =0; i < entry.length; i++)
{
entry[i] = new Person();
}
System.out.println("array of "+ size + " is created.");
}
public void setDataPerson(int age, char gender, String name){
//other statements
}
// Other methods
}
Application
(Sorting and Searching)
public Person search(String searchName) {
Person foundPerson;
int loc = 0;

while (loc < entry.length && !searchName.equals(entry[loc].getName()))


{
loc++;
}
if (loc == count) {
foundPerson = null;
}
else {
foundPerson = entry[loc];
}
return foundPerson;
}
Application
(Searching [Analysis])
Array of Object (Person)
Suppose:
20 age
Source Code searchName = XX
return the number M gender
entry
of object (100)
loc=0 AA name
int loc = 0; entry[0]
loc=1
while (loc < entry[1]
entry.length && ! loc=3 50 age
searchName.equals( entr entry[3]
y[loc].getName())) { F gender
loc++;
}
BB name

entry[99]
15 age
foundPerson =
entry[loc]; M gender

XX name
Application
(Sorting – Based on Name)
public Person[] sort ()
{
Person[] sortedList = new Person[count];
Person P1, P2, temp;
for (int i=0; i<count; i++)
sortedList[i] = entry[i];

int bottom;
boolean exchanged = true;
bottom = sortedList.length -2;

while(exchanged) {
exchanged = false;
for (int i=0; i<=bottom; i++) {
P1 = sortedList[i];
P2 = sortedList[i+1];
if (P1.getName().compareTo(P2.getName()) > 0){
sortedList[i] = P2;
sortedList[i+1] = P1;
exchanged = true;
}
}
bottom--;
}
return sortedList;
}
BEFORE AFTER
SORTING SORTING
entry entry

0 1 2 3 4 …….. 0 1 2 3 4 ……..

Person Person The values are Person Person


Ali Jamal the name of Ali Jamal
Person Person Person Person
Siti Ahmad Siti Ahmad
Person objects.

0 1 2 3 4 …….. 0 1 2 3 4 ……..

sortedList sortedList
Person[]
for (int sortedList
i=0; i<count;
Person[count];
= new
i++)
sortedList[i] = entry[i]; Sorting - Analysis
Application
(Sorting [Analysis])
P1 P2 sortedList
sortedList 0 1 2 3 4 ……..

Source Code Person Person


Jamal
Person Ali Person
while(exchanged) { Siti Ahmad

exchanged = false;
for (int i=0; i<=bottom; i++) {
P1 = sortedList[i];
P2 = sortedList[i+1]; P1 P2
if (P1.getName().compareTo(
P2.getName()) > 0){ sortedList 0 1 2 3 4 ……..
sortedList[i] = P2;
sortedList[i+1] = P1;
exchanged = true;
}
} Person Person
Ali Jamal
bottom--; Person Person
Ahmad
} Siti
Application
(Sorting [Analysis])
P1 P2
sortedList
sortedList 0 1 2 3 4 ……..

Person Person

Source Code Person Siti Person


Ahmad
Jamal
Ali
while(exchanged) {
exchanged = false;
for (int i=0; i<=bottom; i++) {
P1 = sortedList[i];
P2 = sortedList[i+1]; P1 P2
if (P1.getName().compareTo(
P2.getName()) > 0){ sortedList 0 1 2 3 4 ……..
sortedList[i] = P2;
sortedList[i+1] = P1;
exchanged = true;
}
} Person Person
Siti Jamal
bottom--; Person Person
Ahmad
} Ali
Application
(Sorting [Analysis])

AFTER SORTING

Person Person The values are


Ali Siti the name of
Person Person
Ahmad Jamal Person objects.

0 1 2 3 4 ……..

sortedList
The End
Q&A
59

You might also like