0% found this document useful (0 votes)
3 views

Chapter 2 OOP in Java (Part A) - Data Hiding, Objects in Arrays

This document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on defining and using classes and objects, specifically a 'Student' class. It covers attributes initialization, methods, data hiding, and the importance of access modifiers like public and private. Additionally, it discusses the significance of constructor methods for automatic execution during object creation.

Uploaded by

Lee Vico
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 2 OOP in Java (Part A) - Data Hiding, Objects in Arrays

This document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on defining and using classes and objects, specifically a 'Student' class. It covers attributes initialization, methods, data hiding, and the importance of access modifiers like public and private. Additionally, it discusses the significance of constructor methods for automatic execution during object creation.

Uploaded by

Lee Vico
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

C

OM1102
Programming and
Data Structures
Chapter 2

Object-Oriented Programming in Java


Part A
Quick Review on Basic OO Concepts
Attributes initialization
Object as attributes
Data Hiding
Storing Objects in Arrays

Page 1 of 60
Page 2 of 60
Quick Revision: What is an Object

A variable: Can store a piece a value (e.g., int x)

An object:
 Can contain possibly multiple value(s) (of various types)
 Can contain some methods, which can do something for you. E.g.,
 Do some calculations and tell you the result.
 Tell you the values of its variables.
 Update the values of its variables.
 Print something to the screen.
In programming, we can store some complex data using Objects, not
just using variables.

Page 3 of 60
Quick Revision: Object-oriented Programming

 Primitive data types can represent simple data, such as a


number, a character, a true/false value.

 In real life, some data are structured and have multi-parts.

 For example, a Student has a studentId (String), a year


(int), a major (String), a grade (char)

 Thus, Student is a structured data type (with many smaller Student John
SID = S190001
components) year = 3
major = “Eng”
grade = ‘A’

 A Student’s data can be better represented as an Object.


(also called: an instance)

Page 4 of 60
Defining The Student Class of Objects (informally)

Before we can create Student objects to store data, we need


to define what data can be stored inside a Student object.

We start with giving the new type of object a Class name, then we define its
attributes
Class name: Student
Attributes: We have a class of objects,
- SID: String called “Student”, and every
Student object will have a
- Year: int SID, a Year, a Major and a
- Major: String Grade
- Grade: char

ID = S190001
major = Eng
Defining the Student Class of objects

Page 5 of 60
Page 6 of 60
Creating New Student Objects
After defining what a Student Class looks like, we can use it to create
Student Objects.

You can imagine the Student Class is like an object factory that can create Student Objects.

Class name: Student Student John


Attributes:
SID: String
SID = ?
Year: int year = ?
Major: String major = ?
Grade: char grade = ?

Student Mary
The Student Object Factory! SID =?
year =?
major =?
grade =?

Page 7 of 60
Assigning values to attributes in student Objects

After creating Student objects, we can set the values of each object’s attributes.

Student John
SID = S230001 John the Student Object, your SID is “S230001”,
year = 3 your year is 3, your major is “Eng”, your grade is ‘A’
major = “Eng”
grade = ‘A’

Mary the Student Object, your SID is “S230002”,


your year is 1, your major is “Chi”, your grade is ‘B’

Student Mary
SID = S230002
year = 1
major = “Chi”
grade = ‘B’

Page 8 of 60
The Student Class in Java
Class name: Student Defining the Student Class (File name: Student.java)

Attributes:
- SID: String
- Year: int
- Major: String
- Grade: char

ID = S190001

Notes:
 Each file defines one class. (to be more accurate: one public class)
 This class defines what a Student object looks like and what attributes it contains.
(Attributes are also called instance variables.)
 An instance variable can be of a primitive data type (e.g., int) or of a class (e.g.,
String)
 The keyword “public” indicates they can be accessed (seen) by other class’s objects.

Page 9 of 60
Page 10 of 60
The Student Class and Student Objects in Java
1. Defining the Student Class
Class name: Student

Attributes:
- SID: String
- Year: int
- Major: String
- Grade: char 2. Create a new Student object, and assign it to a variable
(You may create as many objects as you like)

ID = S190001
major = Eng
grade = ‘A’
3. Assign values to the attributes in the object

4. Retrieve the values stored in an object

Page 11 of 60
A program that uses a Student object

Student.java

StudentMain.java (or anywhere else)

Note:
As you may have realized already, the scanner is also an object.

Page 12 of 60
Attributes initialization (New!)
Exercise 2.1

Write some codes to create one new Student object as defined


above. Then print out the values of the instance variables imme-
diately without assigning any values to them in your program.
What do you see?

Page 13 of 60
Attribute Type Value
SID, major String
year int
grade char
Exercise 2.1:
Copy and paste your answer here:

Page 14 of 60
Attributes (instance variables) initialization

When you created an object, Java automatically initializes the at-


tributes (instance variables) to some default values.

Type Default values


boolean false
int, long 0
double, float 0.0
char ‘\u0000’ (NULL charac-
ter)
Objects null
(including Strings)
Notes:

In Java, null indicates a reference to an object that does not exist


(yet).

In the previous example, the variables (SID and major) are al-
ready defined, but their values are null, which means that the ob-
jects do not yet exist.

Page 15 of 60
Methods

Page 16 of 60
Quick Revision: Methods

Apart from attributes, objects can also have methods.

An object’s methods are the operations that an object can per-


form, e.g.,
- Update its own attributes.
- Perform some computations.
- Perform I/O operations.
- Call another object’s method.
- And many more!

For example, let’s add a method in our Student class for calculat-
ing the student’s GPA:
Class name: Student
Attributes:
- SID: String
- Year: int
- Major: String
- Grade: char Student John
SID = S190001
Methods: year = 3
- getGPA( ): return a double major = “Eng”
grade = ‘A’

And I know a method


called “Get GPA”.
You can ask me to re-
port my GPA!

Page 17 of 60
getGPA() method
This method will compute and return a GPA score based on
the grade attribute of the student object.

Notes:

The double gpa variable is a local variable. It exists when the


method is called, and ceases to exist when we exit from the method.
(Note that local variable are not initialized by Java.)

There is no “static” at the front of the method declaration (pub-


lic double getGPA()) because the method belongs to a Stu-
dent object. (“static” is only used when the method does not be-
long to any object, which is not our case).

Page 18 of 60
Calling the getGPA() method

We use the object.method() notation to call a method in


an object.

For example:

Calling an object’s method (e.g., stu.getGPA()) is like sending


a message to the target object (stu in our case) and request it to do
something (getGPA() in our case).

Student John
SID = S190001
year = 3 “Get-GPA, please!”
major = “Eng”
grade = ‘A’

I know a method called “It’s 4.0 !”


“Get GPA”. You can ask
me to report my GPA!

Page 19 of 60
Null Pointer Exceptions
Before you call an object’s method, make sure the object already exists
(not NULL)!

Otherwise, you will receive a compilation error, or even the famous


“Null Pointer Exception” error at run time (if the compiler cannot catch
it).

In this case, the expression sid.toUpperCase() in line 10 will re-

sult in a nullPointerException because the SID attribute in the

student object has not been initialized (it is still NULL).

Page 20 of 60
Attributes vs Local Variables

Page 21 of 60
Recall: Attributes
 Also called instance variables.
 Variables that belong to an object.
 Declared OUTSIDE any methods
 Created when an object is created (“new”)
 Can be accessed in any method of the object (or even other
objects if it is public)

Variable a created with the object (value is 1)

It is printed out: 1

Method demo1() is called, a is changed to 3

It is printed out again: 3

Page 22 of 60
Local variables

 Declared inside methods (incl. those in parameter list)


 Created each time the method is called.
 Destroyed when we exit from the method.
 Can be used inside the method only.

Local variable a is created when demo2() is called.


Note: NOT the same one as the attribute a!

Another local variable b created when demo2() is


called.
Note: NOT the same one as the attribute a!
It is printed out: 5

Object lv2 created. Attribute a is 1

Attribute a is printed out again: 1

demo(2) called on the object, and prints out its local


variables a (one of which has the same name as at-
tribute a). However, the attribute a is not changed.
Page 23 of 60

Attribute a is still 1
What is the output?

Output:

Page 24 of 60
Local variables and Objects
In this example, we have an attribute and a local variable of the
same name, but they refer to two separate objects.

Output:

Page 25 of 60
Local variables and Objects
In this example, we have an attribute and a local variable of the
same name, but they refer to two separate objects.

Output:

Page 26 of 60
Next, if the local variable in line 6 of the previous example is re-
moved, line 7 would refer to the Attribute s instead.

Output:

Page 27 of 60
Similarly, TWO local variables with the same name.

Output:

Page 28 of 60
This time, the VALUE of a local variable (which refers to a Student
object) is returned.

Page 29 of 60
Output:

public, private and data hiding

Page 30 of 60
public modifier

Student.java

In our Student class, all attributes are declared as public vari-


ables.

Recall: public means that the attribute (or method) can be ac-
cessed in codes written in another class. For example, we can
read or even modify those values in a Student object from the
StudentMain class.

Page 31 of 60
private modifiers

In contrast, if an attribute is declared as a private variable,


codes in any other places (except in the Student Class) cannot
see or modify the values.

For example, let’s add a private attribute called tempGrade:

Student.java

If we want to change the value of tempGrade, the code must


be inside the Student Class itself as the attribute is private.

Note: in Java, apart from public and private, there are two more types of modi-
fiers, namely protected, and friendly (without a modifier), which we will not
use in this module.

Page 32 of 60
MyDate Class
• Defining a new class called MyDate:
public class MyDate {

int day; // instance variables

int month; // instance variables

int year; // instance variables

public void nextDay () {

/* SKIPPED */ //Method

• Declaring and constructing objects:


MyDate currentDate, endDate;

currentDate = new MyDate();

endDate = new MyDate();

• Accessing instance variables and methods:


currentDate.day = 1;

currentDate.month = 7;

currentDate.year = 2020;

currentDate.nextDay();

Page 33 of 60
Data Hiding
• Suppose you have written the following MyDate class:
1 public class MyDate {

2 int day, month, year;

4 public void nextDay () {

5 // increment day, month and year to the next day

6 }

7 }

• And this is an example of how people may use it:

1 MyDate d = new MyDate();

2 d.day = 31;

3 d.month = 4;

4 d.year = 2020;

Question: What is bad about this approach?

Page 34 of 60
Data Hiding
• A better approach:

public class MyDate {

private int day, month, year;

public void setDay(int targetDay) {

if (targetDay > daysInMonth())

System.err.println(“invalid day ” + targetDay);


else
day = targetDay;
}

public int getDay() {

return day;
}

• We make the instance variables private to prevent ob-


jects of other classes from changing them directly!
• We then provides two methods (setDay( ) and
getDay( )for other objects to call!

Page 35 of 60
Data Hiding
A better approach:

public class MyDate {

private int day, month, year;

public void setDay(int targetDay) {

if (targetDay > daysInMonth())

System.err.println(“invalid day ” + targetDay);


else
day = targetDay;
}

public int getDay() {

return day;
}

}
public class DateUser {

public static void main(String args[]) {

MyDate mydate = new MyDate();

mydate.day = 21; // illegal (not allowed)!!

mydate.setDay(21); // ok!
System.out.println(Mydate.getDay());

}
Page 36 of 60
public vs private methods

Just like attributes, methods in a class can be declared as public or private.

 public
The variable, or method is visible to objects any class, anywhere.

 private
The variable or method can be accessed only by objects in the same class as current
object.

Note: if neither the private or public modifier is declared before a variable or method (i.e., no modifier is provided), the

default access right would be applied. In this case, the method can be accessed by any class in the same package. This

has the same effect as using the “friendly” modifier, which is not further discussed in this module).

Data Hiding
Page 37 of 60
• Make your instance variables private, and provide getter and setter methods
for accessing the data where necessary. (To provide a separation between
the interface and implementation)
• Advantages:
o The object can control how its attributes can be changed!
o The object can decide what can be seen by other objects!
o Other people do not need to know how data is represented internally. They only need
to know how to call the (public) methods!
o Prevent unintentional (or illegal) changes to the data (instance variables)

Using data hiding does not make your code run faster, but it helps to make your code easier to
maintain.

Page 38 of 60
Introduction to Object-oriented Programming:

 Constructor methods
 Overloading

Page 39 of 60
Constructor methods

 Sometimes, we want to execute certain codes automatically when an object is


created.
 To do so, we can use constructor methods, which is run when we create (“new”)
an object.
 Normally, constructors perform initialization for the attributes of objects.

 The constructor method has the same name as the class.

Page 40 of 60
Example: A Circle Class
Let’s first define a class of Circle objects
(Circle.java)

And a class that uses Circle objects


(DemoCircleClass.java)

Question: can we assign values to the at-


tributes (e.g., radius) at the same time
when the objects are created?
Answer: Yes, we can, by using constructor methods
Page 41 of 60
A class that defines Circle objects (Circle.java)

A class that uses Circle objects (DemoCircle.java)

The constructor public Circle(double r) will run automatically every

time a new Circle object is created (e.g., by calling new Circle(5.0) )

Page 42 of 60
Constructor Overloading
It is possible to provide more than one constructor. For example:
Circle.java

Which one will be called depends on the arguments is supplied:


Circle c = new Circle ( ); // The first constructor is called

Page 43 of 60
Method Overloading
Just like constructors, any methods in a class can be overloaded too by providing more than one version.

For example:

Here, the method named displayMessage( ) is overloaded. Which version would be called depends

on the arguments provided.

Page 44 of 60
Calling overloaded methods

(A)

(B)

Given the same class definition as above, and the following calling

method:

Will call method (A)


above

Will call method (B)


above
The output would be:
My name is Alan

My name is Peter

I am 18 years old.

Page 45 of 60
Introduction to Object-oriented
Programming:

Instance variable vs local variable


The this keyword

Page 46 of 60
The this keyword
Sometimes, a local variable in a method has the same

name as an instance variable, for example:

An instance variable
(attribute)

A local variable

 Here, the radius in line 4 and the radius in line 6 are two differ-

ent variables.

 The first one (line 4) is an instance variable that can be accessed


anywhere within the class.

 The second one (line 6) is a local variable and an argument, that ex-
ists in the method only.

Question: which one (instance variable or local variable)

is being referred to in line 8?

Answer: the nearest one (local)

Page 47 of 60
The this keyword
 Under such situation, the local variable will be referred to.
 If we need to refer to the instance variable, we can use the this keyword, for example:

 The this keyword actually refers to the current object itself.

 In this case, this.radius refers to the attribute in line 4, whereas the un-qualified version (the second ra-
dius line 8) refers to the local variable (the argument) in line 6.

 The this keyword is not needed (optional) in other situations where there are no such confusions.

Exercise 2.2: BankAccount with Data-hiding


Page 48 of 60
Write a BankAccount class with the following attributes
1. accountNumber (String)
2. customerName (String)
3. balance (double)
 All attributes must be declared as private.
 Provide a suitable constructor.
 Provide setters and getters methods for all three attributes.
Tips: explore the auto-insert-code (Alt-insert) tool in NetBeans.

Object-oriented Programming in Java:


Page 49 of 60
Storing Objects in Arrays

Page 50 of 60
Saving BankAccount Objects in an Array

 Create an Array for holding up to 10 bank accounts.

 Create 3 accounts (with names, account number and balance)


and put them into the first 3 positions of the array.

 Use a For Loop to Print out a report of all accounts with bal-
ance >= 10000.

 Use a For Loop to Print out all account details.

Page 51 of 60
Exercise 2.2 (continue):

Create an Array for holding up to 10 bank accounts.

Note: at this point, the array is still EMPTY. We do not have


any Bank Account objects yet!

accounts

What would happen if you look for accounts[0] now?

Page 52 of 60
Exercise 2.4 (continue):

 Create 3 accounts (with names, account number and balance)


and put them into the first 3 positions of the array.

accounts

“Peter” “Simon” “Mary”


“00001” “00002” “00003”
5000 10000 20000

ac1 ac2 ac3

Page 53 of 60
 Create 3 accounts (with names, account number and balance)
and put them into the first 3 positions of the array.

accounts

“Peter”
“00001”
5000

ac1

Page 54 of 60
 Create 3 accounts (with names, account number and balance)
and put them into the first 3 positions of the array.

accounts

“Peter”
“00001”
5000

ac1

Page 55 of 60
 Use a For Loop to Print out a report of all accounts
 Remember to check for null as some slots are empty!

accounts

“Peter” “Simon” “Mary”


“00001” “00002” “00003”
5000 10000 20000

Page 56 of 60
a

 Use a For Loop to Print out all account details with balance >= 10000

Page 57 of 60
Completed Program Code

Page 58 of 60
Alternative version using Enhanced For Loop

Page 59 of 60
Page 60 of 60

You might also like