[go: up one dir, main page]

0% found this document useful (0 votes)
116 views40 pages

Chapter 4 - Part 1

The document discusses object-oriented programming concepts such as classes, objects, class diagrams, and constructors. It explains that classes define objects of the same type through variables and methods, while objects are instances of classes. The document also covers declaring and creating objects, accessing object properties and methods, and using constructors to initialize objects.

Uploaded by

Jia Wei Loo
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)
116 views40 pages

Chapter 4 - Part 1

The document discusses object-oriented programming concepts such as classes, objects, class diagrams, and constructors. It explains that classes define objects of the same type through variables and methods, while objects are instances of classes. The document also covers declaring and creating objects, accessing object properties and methods, and using constructors to initialize objects.

Uploaded by

Jia Wei Loo
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/ 40

AACS2204 Object-Oriented Programming Techniques

Objects and Classes


Chapter 4 Part 1

Learning Outcomes
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.
Explain how to access objects via object reference
variables.
Differentiate between classes and objects.
Write constructors in classes.
2

1. Introduction to OO Programming
Concepts
 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 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.

Classes
 Classes are constructs that define objects of the same
type.

 A class uses
 variables to define data fields and
 methods to define behaviors.
 An object is an instance of a class

public class Circle1 {


double radius = 1.0;
double getArea() {
return Math.PI * radius * radius;
}
}
public class TestCircle1 {
public static void main(String[] args) {
Circle1 c1 = new Circle1();
System.out.println(Radius " + c1.radius + Area " + c1.getArea());
// Modify circle radius
c1.radius = 100;
System.out.println(Radius " + c1.radius + Area " + c1.getArea());
Circle1 c2= new Circle1();
c2.radius = 5;
System.out.println(Radius " + c2radius + Area " + c2.getArea());
5
}

Classes
A class can also provide a special type of methods, known as
constructors, which are invoked to construct objects from the
class.
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}

Data field

Constructors

/** Construct a circle object */


Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}

Method

}
6

UML Class Diagram


Circle

UMLClass Diagram

Class name

radius: double

Data fields

Circle()

Constructors and
Methods

Circle(newRadius: double)
getArea(): double

circle1: Circle
radius: 10

circle2: Circle
radius: 25

circle3: Circle

UMLnotation
for objects

radius: 125
7

2. Declaring, Creating & Accessing


Object
 To reference an object, assign the object to a
reference variable.

 To declare a reference variable, use the syntax:


ClassName objectRefVar;

myCircle

null

Example:
Circle myCircle;
Note : no circle object has been created.
8

Creating Object
To actually create a Circle object, use the following
statement.

myCirle = new Circle(5.0);


myCircle
object reference
variable

reference value

: Circle
radius: 5.0

The new operator dynamically allocates (that is,


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

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

: Circle
radius: 5.0
10

Accessing Objects
myCircle

Referencing the objects data:


objectRefVar.data

reference value

: Circle
radius: 5.0

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


Invoking the objects method:


objectRefVar.methodName(arguments)
e.g.,
System.out.println(myCircle.getArea());
11

3. Constructors
 Constructors must have the same name as the class itself.
 Constructors do not have a return type - not even void.
class Circle {
/** The radius of this circle */
double radius
Circle()
{ = 1.0;

/** Construct a circle object */


Circle() {
}

Circle(double
newRadius)
/** Construct a circle
object */ {
Circle(double
newRadius) {
radius
=
newRadius;
radius = newRadius;
} }
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}

Data field

Constructors

Method

}
12

Constructors
 A constructor with no parameters is referred to as a noarg constructor.

class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}

Data field

Constructors

/** Construct a circle object */


Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}

Method
13

Creating Objects Using Constructors


 Constructors are invoked using the new operator when
an object is created. Constructors play the role of
initializing objects.
cla ss C ircle {
/ ** T he ra dius of t his
d oubl e rad ius = 1.0 ;
/ ** C onstr uct
C ircl e() {
}

a cir cle

circl e */

objec t */

/ ** C onstr uct a cir cle objec t */


C ircl e(dou ble newRa dius ) {
rad ius = new Radiu s;
}

new ClassName();
Example:
new Circle();
new Circle(5.0);

/ ** R eturn the area of this circ le */


d oubl e get Area () {
ret urn r adiu s * r adiu s * 3 .141 59;
}
}

14

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.

cla ss C ircle {
/ ** T he ra dius of t his circl e */
d oubl e rad ius = 1.0 ;
/ ** C onstr uct a cir cle objec t */
C ircl e() {
}
/ ** C onstr uct a cir cle objec t */
C ircl e(dou ble newRa dius ) {
rad ius = new Radiu s;
}

Eg Circle( ){ }

 This constructor, called


a default constructor, is
provided automatically
only if no constructors
are explicitly declared in
the class.

/ ** R eturn the area of this circ le */


d oubl e get Area () {
ret urn r adiu s * r adiu s * 3 .141 59;
}
}

15

animation

Trace Code (1)


Declare myCircle

Circle myCircle = new Circle(5.0);

myCircle

no value

SCircle yourCircle = new Circle();


yourCircle.radius = 100;

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

16

animation

Trace Code (2)


Circle myCircle = new Circle(5.0);

myCircle

no value

Circle yourCircle = new Circle();


yourCircle.radius = 100;

: Circle
radius: 5.0

Create a Circle object

17

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

: Circle
radius: 5.0

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.
18

animation

Trace Code (4)


myCircle

reference value

Circle myCircle = new Circle(5.0);

: Circle

Circle yourCircle = new Circle();


yourCircle.radius = 100;

radius: 5.0

yourCircle

no value

Declare yourCircle

19

animation

Trace Code (5)


myCircle reference value
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;

: Circle
radius: 5.0

no value

yourCircle

: Circle
Create a new
Circle object

radius: 0.0

20

animation

Trace Code (6)


reference value

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

: Circle

yourCircle.radius = 100;

radius: 5.0

yourCircle
Assign object
reference to
yourCircle

reference value

: Circle
radius: 1.0

21

animation

Trace Code (7)


reference value

myCircle
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;

: Circle
radius: 5.0

yourCircle

reference value

: Circle
Change radius in
yourCircle

radius: 100.0

22

4. Classes vs Objects
A

class is a template that defines the form


of an object.
Class Name: BankCustomer

A class consists of 2 parts:


Data




Members

Data or properties of a class.


The nouns of the class.
Represents the state of its objects.

Method





Members

Data member(s)
Name
I/C Number
Address
Balance
Method member(s)
Create new Customer
Deposit money
Withdraw money
Transfer money

Functions or actions of a class,


The verbs of the class.
The code that will operate on the data of the class.
Implementation of its objects behaviors.

23

Classes vs Objects
 An object is an instance of

exactly one class.


 A class is a logical abstraction.
- Defines what data to store
and what actions we can
operate on the data.
 Only when we create an object,
then we have a actual physical
representation of that class
exists in memory.
 Note: One object can have only
one class while one class can
have multiple objects.

Class Name: BankCustomer


Data member(s)
Name
I/C Number
Address
Balance
Method member(s)
Create new Customer
Deposit money
Withdraw money
Transfer money

Tan Chee
193, Jln Big, KL
451021-9-6390
RM4066.67

Ali Mohd
23,
JlnHoe
A1, Ipoh
Tan
510215-6-5533
193, Jln Big, KL
RM456.98
950102-9-9990
RM32.00

5. Defining a Class
The general form of a class definition is show here:
public class <class name> {
//declare instance variables
type var1;
type var2
...
type varN
//declare methods
Method 1
Method 2
.
Method n

Data part

Method part

}
25

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).

26

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.
 A class declaration is only a type description, it
DOES NOT create an actual object.
27

Creating a Vehicle Object




To actually create a Vehicle object, use the following


statement.

Vehicle car1 = new Vehicle();


// default constructor was invoked

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


physical reality).
28

Creating a Vehicle Object


 Each time the instance of a class is created, the
object contains its own copy of each instance
variable defined by the class.

Vehicle car1 = new Vehicle();


Vehicle car2 = new Vehicle()

car2

29

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
passenger
fuelCap
mpg

null
0
0
0

30

Accessing Data Members in the Vehicle Object


class Vehicle{
String plateNo;
car
int passengers;
int fuelCap;
int mpg;
plateNo
}
passengers
public class VehicleDemo{
fuelCap
public static void main(Sting args [ ]) {
mpg
Vehicle car = new Vehicle();
car. plateNo = WWW 1234;
car. Passengers = 4;
car. fuelCap = 20;
car. mpg = 10;
System.out.print(Plate No: + car.plateNo );
System.out.print(Number of passengers: + car.passengers );
System.out.print( Fuel capacity: + car.fuelCap + gallons );
System.out.print( Average Fuel Consumption: + car.mpg +
miles);
}

Note

class Vehicle{
String plateNo;
int passengers;
 If there is more than one
int fuelCap;
class in a file, only one
int mpg;
class can be a public }
class.
public class VehicleDemo{
public static void main(String args [ ]) {
 The public class must
Vehicle car = new Vehicle();
have the same name as
car. plateNo = WWW 1234;
the file name.
car. Passengers = 4;
 The main method must
car. fuelCap = 20;
car. mpg = 10;
be in a public class.
System.out.print(Plate No: +
car.plateNo );
9..
}
}
32

Class Methods
 Methods are subroutines
 What the class can do or
perform.
 They provide access to and
manipulate the data
members of the class.
 We will add a method called
range() to the Vehicle
class to return fuel
capacity * miles per
gallon.

class Vehicle {
String plateNo;
int passengers;
int fuelCap;
int mpg;
}
// Vehicle class definition
class Vehicle {
String plateNo;
int passengers;
int fuelCap;
int mpg;
int range() {
return fuelCap * mpg;
}
}

33

Class Method Invocation


class Vehicle {
String plateNo;
int passengers;
int fuelCap;
int mpg;
int range() {
return fuelCap * mpg;
}
}
public class VehicleDemo2 {
public static void main(Sting args [ ]) {
Vehicle car = new Vehicle();
car. plateNo = WWW 1234;
car. Passengers = 4;
car. fuelCap = 20;
car. mpg = 10;
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);
}
}
34

call range() method

Constructors
 A no-arg constructor
with an empty body is
implicitly declared if a
class is declared without
constructors.
Eg Vehcle( ){ }
This approach
would never be
used in
professionally
written Java code!

class Vehicle {
String plateNo;
int passengers;
int fuelCap;
int mpg;
int range() {
return fuelCap * mpg;
}
}
public class VehicleDemo {
public main(Sting args [ ]) {
Vehicle car = new Vehicle();
car. plateNo = WWW 1234;
car. Passengers = 4;
car. fuelCap = 20;
car. mpg = 10;
.
}
}

35

Adding a Parameterized Constructor to


Vehicle Class
// Filename: VehicleDemo3.java
class Vehicle{
String plateNo;
int passengers;
int fuelCap;
int mpg;
//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; }
}
36

Calling the Parameterized Constructor


Thus, we no longer set data one by one
car.plateNo = WWW 1234;
car.Passengers = 4;
car.fuelCap = 20;
car.mpg = 10

This statement invokes


a constructor.

public class VehicleDemo3 {


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

37

Class Constructors


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.
38

Class Constructors
Constructors

may be
 Constructors with
parameters
(parameterized
constructors)


No-argument / no-arg
constructors, e.g.
Vehicle() {
plateNo = ;
passenger = 0;
}
Default Constructors

class Vehicle{
String plateNo;
int passengers;
int fuelCap;
int mpg;
//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;
}

Reference
Main text:
Chapter 8

Extracted from slides by Liang, Introduction to Java Programming, 9th


Edition 2013, Prentice Hall
40

You might also like