You are on page 1of 48

AACS2204 Object-Oriented Programming Techniques

Chapter 4 – Part 1

Objects and Classes

1
Learning Outcomes (1)
At the end of this lesson, you should be able to
■ Describe objects and classes.
■ Use UML graphical notations to model classes and objects.
■ Declare a class and create an object from a class.

2
Procedural Paradigm VS. Object-oriented
Paradigm
Procedural Paradigm (PP) Object-Oriented Paradigm (OOP)
Data & methods are loosely Couples data and methods together
coupled. into objects.
Software design focuses on Software design focuses on objects
designing methods. and operations on objects.

As data and operations on the data Places data and the operations
are separate, this methodology pertaining to the data within a single
requires sending data to methods. entity called an object.
OO Programming Concepts (1)
▪ Object-oriented programming (OOP) involves programming using
objects.
▪ An object represents an entity in the real world that can be
distinctly identified, e.g. a student, a desk, a circle, a button, a loan.
▪ An object is an instance of a class.
▪ An object has a unique identity, state and behaviors.
▪ The state of an object consists of a set of data fields (also
known as properties) with their current values.
▪ The behavior of an object is defined by a set of methods.

4
Objects

▪ An object has both a state and behavior.


▪ The state defines the object.
▪ The behavior defines what the object does. 5
Example
public class Circle {

double radius;

double getArea() {
return Math.PI * radius * radius; public class TestCircle {
} public static void main(String[] args) {

} Circle c = new Circle(); Object

c.radius = 10;
System.out.println(“Radius “ + c.radius );
Circle template
System.out.println(“Radius “ + c.getArea());
}
}
Objects
template template

Object 1 Object 2
Object 3
Classes (1)
▪ Classes are constructs that define objects of the same type.
▪ A class uses
▪ variables to define data fields and
▪ methods to define behaviors.
▪ Additionally, a class provides a special type of methods, known
as constructors, which are invoked to construct objects from
the class.

8
Classes (2)

9
UML Class Diagram
Declaring Object Reference Variables
▪ To reference an object, assign the object to a reference variable.
▪ To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example: myCircle reference value


Circle myCircle;
myCircle = new Circle(5.0);
Declaring/Creating Objects in a Single Step
ClassName objectRefVar = new ClassName();
■ Example:

Assign object reference Create an object

Circle myCircle = new Circle(5.0);


myCircle reference value
myCircle
Accessing Objects reference value

■ Referencing the object’s data:


objectRefVar.data

e.g.,
Circle myCircle = new Circle(10);
System.out.println(myCircle.radius);

■ Invoking the object’s method:


objectRefVar.methodName(arguments)

e.g.,
System.out.println(myCircle.getArea());

13
A Simple Circle Class
class Circle { public class TestCircle {
private double radius; public static void main(String[] args) {
public Circle() {
Circle c1 = new Circle();
this(1.0);
}
Circle c2 = new Circle(5);

public Circle(double radius) { System.out.println(“Radius = " +


this.radius = radius; c1.getRadius() + "\n\t Area = " +
} c1.findArea() );

public double getRadius() { System.out.println("Radius = " +


return radius; c2.getRadius() + "\n\t Area = " +
}
c2.findArea() );
public double findArea() {
return Math.PI * radius * radius; }
} }
}
animation

Trace Code (1)


Circle myCircle = new Declare myCircle
Circle(5.0);

SCircle yourCircle = new myCircle no value

Circle();

yourCircle.radius = 100;

Note:
■ myCircle is an object reference. It will be used to
store the address of a Circle object.
animation

Trace Code (2)


Circle myCircle = new Circle(5.0);
myCircle no value

Circle yourCircle = new Circle();

yourCircle.radius = 100;

Create a Circle
object
animation

Trace Code (3)


Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle(); myCircle reference value

yourCircle.radius = 100;

Assign object reference to


myCircle

Note:
■ The address of the newly created object (with radius 5.0) is
assigned to the object reference myCircle, i.e. myCircle
will now be “pointing to” the Circle object.
animation

Trace Code (4)


myCircle reference value
Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

yourCircle no value

Declare
yourCircle
animation

Trace Code (5)


myCircle reference value
Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

yourCircle no value

Create a new Circle


object
animation

Trace Code (6)


Circle myCircle = new Circle(5.0); myCircle reference value

Circle yourCircle = new Circle();

yourCircle.radius = 100;

yourCircle reference value

Assign object
reference to
yourCircle
animation

Trace Code (7)


Circle myCircle = new myCircle reference value

Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

yourCircle reference value

Change radius in
yourCircle
Review of learning outcomes

You should now be able to


⮚ Describe objects and classes.
⮚ Use UML graphical notations to model classes and objects.
⮚ Declare a class and create an object from a class.
AACS2023
Object-Oriented Programming

Objects and Classes

Chapter 4 – Part 2
Learning Outcomes (2)
At the end of this lesson, you should be able to
■ Differentiate between classes and objects.
■ Explain how to access objects via object reference
variables.
■ Write constructors in classes.
Classes
⮚ A class is a template that defines the form of an object.
⮚ A class consists of 2 parts: Class Name: BankCustomer
■Data Members
Data member(s)
■Data or properties of a class. • Name
■The nouns of the class. • I/C Number
• Address
■Represents the state of its objects. • Balance
■Method Members
Method member(s)
■ Functions or actions of a class,
• Create new Customer
■ The verbs of the class. • Deposit money
■ The code that will operate on the data of the class. • Withdraw money
■ Implementation of its objects’ behaviors. • Transfer money
Objects vs Classes (1)
Class Name: BankCustomer
■An object is an instance of exactly one
Data member(s)
class. • Name
■A class is a logical abstraction. - • I/C Number
• Address
Defines what data to store and what • Balance
actions we can operate on the data. Method member(s)
■Only when we create an object, then • Create new Customer
• Deposit money
we have a actual physical • Withdraw money
• Transfer money
representation of that class exists in
memory.
■Note: One object can have only one Tan Chee Ali Mohd
193, Jln Big, KL 23, Jln A1, Ipoh
class while one class can have multiple 451021-9-6390 510215-6-5533
RM4066.67 RM456.98
objects.
Objects vs Classes (3)

Are they the same? Yes…No…. Why ???


Defining a Class
The general form of a class definition is show here:
public class <class name> {
//declare instance variables
type var1;
type var2 Data part
...
type varN

//declare methods
Method part
Method 1
Method 2
…….
Method n
}
Case Study: The Vehicle Class
⮚ Objective: To develop a class that represents vehicles
such as cars, vans and trucks.
⮚ This class is called Vehicle and it will store the
following information about a vehicle:
■ the plate number,
■ the number of passengers that it can carry,
■ its fuel capacity and
■ its average fuel consumption (in miles per gallon).
Data Members of the Vehicle Class
// Vehicle class definition
class Vehicle {
String plateNo;
int passengers;
int fuelCap;
int mpg;
}
⮚ A class definition creates a new data type.
⮚ In this case, the new data type is called Vehicle.
⮚ We will use this name to declare objects of type
Vehicle.
Creating a Vehicle Object (1)
⮚ A class declaration is only a type description, it DOES NOT
create an actual object.
⮚ To actually create a Vehicle object, use the following
statement.

Vehicle car = new Vehicle();

Class name object reference variable

⮚ car will be an instance of Vehicle (thus, it will have


“physical” reality).
Creating a Vehicle Object (2)
Vehicle car1 = new Vehicle();

The new operator dynamically allocates (that is, allocates at


run time) memory for an object and returns a reference to it.

car1 plateNumber
passenger
fuelCap
mpg

Each time the instance of a class is created, the object


contains its own copy of each instance variable defined by
the class.
Default Value for a Data Field
⮚ The default value of a data field is
■ null for a reference type
■ 0 for a numeric type
■ false for a boolean type
■ '\u0000' for a char type.

car1 plateNumber null


passenger 0
fuelCap 0
mpg 0

33
Accessing Data Members in the Vehicle Object
class Vehicle{
String plateNo; car
int passengers; plateNo
int fuelCap; passengers
int mpg; fuelCap
}
mpg
public class VehicleDemo{
public static void main(Sting args [ ]) {
Vehicle car = new Vehicle();
car. plateNo = “WWW 1234”; Plate No: WWW 1234
car. Passengers = 4; Number of passengers: 4
car. fuelCap = 20; Fuel capacity: 20 gallons
car. mpg = 10; Average Fuel Consumption: 10 miles
System.out.print(“Plate No: ” + car.plateNo );
System.out.print(“Number of passengers: ” + c ar.passengers);
System.out.print( “ Fuel capacity: ” + car.fuelCap + “ gallons” );
System.out.print( “Average Fuel Consumption : ” + car.mpg + “miles”);
}
}
Note
⮚ If there is more than one class in a file, only one class can be a
public class.
⮚ The public class must have the same name as the file name.
⮚ The main method must be in a public class.

class Vehicle{
……
}
public class VehicleDemo{
public static void main(Sting args [ ]) {
…..
}
}
Class Methods (1)
⮚ Methods are subroutines
// Vehicle class definition
⮚What the class can do or class Vehicle {
perform. String plateNo;
⮚They provide access to and int passengers;
int fuelCap;
manipulate the data members int mpg;
of the class.
⮚ We will add a method called int range() {
return fuelCap * mpg;
range() to the Vehicle class }
to return fuel capacity * }
miles per gallon.
Class Method Invocation
class Vehicle { public class VehicleDemo2 {
String plateNo; public static void main(Sting args [ ]) {
int passengers; Vehicle car = new Vehicle();
int fuelCap; car. plateNo = “WWW 1234”;
int mpg; car. Passengers = 4;
int range() { car. fuelCap = 20;
return fuelCap * car. mpg = 10;
mpg; System.out.print(“Plate no: ” + car.plateNo);
}
System.out.print(“\nNo. of passengers: ” +
}
car.Passengers );
System.out.print(“\nFuel capacity: ” +
car.fuelCap + “ gal”);
System.out.print(“\nAvg fuel consumption: ” +
car.mpg + “ mpg”);
System.out.println(“Range: ” + car.range() +
“ miles”);
} call range() method
Constructors (1)
Constructors are a special kind of method that are invoked to
construct objects. Circle c1 = new Circle(5.0);

Circle() {
}

Circle(double newRadius) {
radius = newRadius;
}
Constructors (2)
⮚ A constructor with no
parameters is
referred to as a no-arg
constructor.
⮚ Constructors must
have the same name
as the class itself.
⮚ Constructors do not
have a return type -
not even void.
Creating Objects Using Constructors
⮚ Constructors are
invoked using the new
operator when an
object is created.
Constructors play the
role of initializing
objects.

new ClassName();
Example:
new Circle();
new Circle(5.0);
Default Constructor
▪ A class may be declared
without constructors. In this
case, a no-arg constructor with
an empty body is implicitly
declared in the class.
Eg Circle( ){ }
▪ This constructor, called a
default constructor, is provided
automatically only if no
constructors are explicitly
declared in the class.
The new Operator
■ What actually took place when the new operator was used
in the main method of VehicleDemo.java?
■ A Vehicle object was created by the default constructor for Vehicle
and its fields were initialized to their default values.

public class VehicleDemo {


this approach would never be public … main(Sting args [ ]) {
used in professionally written Vehicle car = new Vehicle();
Java code!
car. plateNo = “WWW 1234”;
There is a better way to
initialize values to object car. Passengers = 4;
car. fuelCap = 20;
Constructor
car. mpg = 10;
……….
Adding a Parameterized Constructor to Vehicle Class
// Filename: VehicleDemo3.java
class Vehicle{ Constructor:
String plateNo; ✔ Same name as class name
int passengers;
✔ No return type
int fuelCap;
int mpg; ✔ Receive parameter to set
values to data member
//this is a constructor for Vehicle
Vehicle (String no, int p, int f, int m){
plateNo = no;
passengers = p;
fuelCap = f;
mpg = m;
}

//return the range


int range(){ return fuelCap * mpg; }
}
Calling the Parameterized Constructor
Thus, we no longer set data one by one

car.plateNo = “WWW 1234”;


car.Passengers = 4;
car.fuelCap = 20; This statement invokes a
car.mpg = 10 constructor.

public class VehicleDemo3 {


public static void main(Sting args []){
Vehicle car = new Vehicle(“WWW 1234”, 4, 20, 10);

Class Constructors (1)
⮚ Recall that a constructor
■ is a special method.
■ initializes an object when it is created.
■ has the same name as the class name.
■ has no explicit return type.
⮚ We use constructors to
■ give initial values to the instances variables defined by the
class.
■ perform any other startup procedures required to create a
fully formed object.
Class Constructors (2)
■Constructors may be class Vehicle{
■ Constructors with parameters
….
(parameterized constructors)
//this is a constructor for Vehicle
■ No-argument / no-arg Vehicle (String No, int p, int f, int
constructors, e.g. m){
plateNo = No;
Vehicle() { passengers = p;
plateNo = “”; fuelCap = f;
mpg = m;
passenger = 0; }
}
….
■ Default Constructors
}
Review of learning outcomes
You should now be able to
■ Differentiate between classes and objects.
■ Explain how to access objects via object reference variables.
■ Write constructors in classes.

47
To Do
■ Review the slides and source code for this chapter.
■ Read up the relevant portions of the recommended text.
■ Complete the remaining practical questions for this chapter.
■ We shall selectively discuss them during class.

48

You might also like