You are on page 1of 55

COMP 212 –

Programming II
1 – Objects and Classes(1)

1
1– Objects and Classes - Outline

Object Oriented Programming

Object and Classes

Constructor

Data Field Encapsulation

2
Object-Oriented Programming
(OOP)
➢ Procedural programming is about writing a function that
perform some calculations on the data.
➢ Object-oriented programming (OOP) is about creating
objects that contain related data and methods.

3
Object-Oriented Programming
(OOP)
Procedural programming

1. double x = 0.5;

2. double y = f(x);

3. double z = g(y);

4. double result = h(z);

4
Object-Oriented Programming
(OOP)
➢ Object-oriented programming (OOP) involves
programming using objects.
➢ An object represents an entity in the real world that can
be distinctly identified. For example, a student, a desk,
a circle, a button, and even a loan can all be viewed as
objects.
➢ An object has a unique identity, state, and behavior.
➢ 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.

5
➢ Objects group together
➢ Primitives (int, double, char, etc...)
➢ Objects (String, etc...)

Customer
Object- String name
Oriented int id

Programming double payment

(OOP) ➢ What if there’re many customers??


➢ String name1, name2, name3, ...
➢ int id1, id2, id3, ...
➢ double payment1, payment2, pyament3, ...

6
Object-Oriented Programming
(OOP)
➢ Why use classes?

public class Customer {


String name;
int id;
double payment;
} Customer

customer1 customer2 customer3 ......

7
Object-Oriented Programming
(OOP)
➢ Object
➢ An object has a state and behavior.
➢ The state defines what the object is. Each object has its own state.
➢ The behavior defines what the object does. It is defined in the Class.

A Class Template Class Name: Customer

Data Fields:
Name is

Methods:
checkPayment()

3 Objects of Customer Object1 Customer Object2 Customer Object3


the Customer Class
Data Fields: Data Fields: Data Fields:
Name is Peter Name is David Name is Jack
8
Objects

➢ Create a single object = an “instance” of the class

Customer customer1 = new Customer();

9
Objects

➢ Create a single object = an “instance” of the class

The "new" keyword/operator


Class Name
to create an object

Customer customer1 = new Customer();

Reference of an object

Constructor of the Customer class

10
Objects

➢ In an object:
➢ Common variables are shared among certain operations.
➢ The variables are global only to these operations, but
not to others.
➢ The shared variables can be packaged into a common context
for the related operations.

➢ Using objects improves software reusability and makes programs


easier to develop and easier to maintain (flexibility, modularity,
clarity).
➢ Programming in Java involves thinking in terms of objects.
➢ A Java program can be viewed as a collection of cooperating objects.

11
Classes

➢ Classes are constructs that define objects of the same


type. A Java 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.

12
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
13
Classes
UML Class Diagram Circle Class name

radius: double Data fields

Circle() Constructors and


Circle(newRadius: double) methods
getArea(): double

circle2: Circle circle3: Circle UML notation


circle1: Circle
for objects
radius = 1.0 radius = 25 radius = 125

• "radius" is the data field, defined as variable.


• Each instance of the class has its own copy of the variables, so they are
called instance variables.
• getArea() is a method, defined for all instances of the class.
• When a method is invoked, it operates only on a particular instance:
For example: circle1.getArea() return the area of circle1, which calculated
using the radius of circle1.
14
Example: Defining Classes
and Creating Objects
➢ Objective:
Demonstrate
creating objects, accessing
data, and using methods.

TestCircle1 Run

15
Example: Defining Classes
and Creating Objects
➢ Objective:
Demonstrate
creating objects, accessing
data, and using methods.
TV

TestTV Run

16
Class Circle {
private double x, y;
private double radius;
public Circle(double newRadius) {
radius = newRadius;
}
A Class public double getArea() {
return Math.PI*radius*radius;
Definition }
public boolean contains(double x, double y)
{
double dx = x – this.x;
double dy = y - this.y;
return dx*dx + dy*dy <= radius*radius;
}
}

17
Constructors

Circle() { Constructors are a


} special kind of
methods that are
Circle(double newRadius) { invoked to construct
radius = newRadius; objects.
}

18
Constructors

➢ 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.
➢ Constructors are invoked using the new operator when
an object is created. Constructors play the role of
initializing objects.

19
Default Constructors

➢ A class may be declared without constructors. In this


case, a no-arg constructor with an empty body is
implicitly declared in the class.

Example:

Circle() {
}

This constructor, called a default constructor, is


provided automatically only if no constructors are
explicitly declared in the class.

20
Creating Objects Using
Constructors
new ClassName(); //creates a new instance and returns its reference

➢ Example:

new Circle();

new Circle(5.0);

21
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:

Circle myCircle;

22
Declaring/Creating Objects
in a Single Step
➢ ClassName objectRefVar = new ClassName();

Assign object reference Create an object


➢ Example:

Circle myCircle = new Circle();

23
Accessing Objects

➢ Referencing the object’s data:

objectRefVar.data

e.g., myCircle.radius

➢ Invoking the object’s method:

objectRefVar.methodName(arguments)

e.g., myCircle.getArea()

24
Trace Code
Declare myCircle

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100;

25
Trace Code, cont.

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

yourCircle.radius = 100;
: Circle

radius: 5.0

Create a circle

26
Trace Code, cont.

Circle myCircle = new Circle(5.0);


myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; Assign object reference


to myCircle : Circle

radius: 5.0

27
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

Declare yourCircle

28
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

: Circle
Create a new radius: 0.0
Circle object

29
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

Assign object reference


to yourCircle : Circle

radius: 0.0

30
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

: Circle
Change radius in radius: 100.0
yourCircle

31
More on Constructors and the
“this” Instance
➢ Constructor, which has exactly the same name as the defining
class, can be overloaded.
➢ One constructor can invoke other constructors of the class using
“this” before any other statements.

Class Circle {
public Circle(double x, double y, double radius)
{
this.x = x; this.y = y; this.radius=radius;
}
public Circle(double radius)
{ this(0.0, 0.0, radius)}

}
32
More on Constructors and the
“this” Instance
➢ Within a method, “this” refers to the instance
which the method is operating on.
➢ Within a method, if a name is not declared as a local variable or
a parameter, it is prefixed with “this.” by default.

Class Circle {
public Circle(double x, double y, double radius)
{
this.x = x; this.y = y; this.radius=radius;
}
public Circle(double radius)
{ this(0.0, 0.0, radius)}

}
33
More on Constructors and the
“this” Instance
➢ A local variable or a parameter hides the field with the same
name, to access the field, “this.” must be specified explicitly.
➢ When invoking new Circle(0.0,0.0,3.0),
this.radius in the constructor refers to the field radius of the
newly created instance.

Class Circle {
public Circle(double x, double y, double radius)
{
this.x = x; this.y = y; this.radius=radius;
}
public Circle(double radius)
{ this(0.0, 0.0, radius)}

}
34
Calling Overloaded
Constructor
public class Circle {
private double radius;

public Circle(double radius) {


this.radius = radius;
} this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
} this is used to invoke another constructor

public double getArea() {


return this.radius * this.radius * Math.PI;
}
} Every instance variable belongs to an instance represented by this,
which is normally omitted
35
Reference Data Fields

➢ The data fields can be of reference types. For example,


the following Student class contains a data field name of
the String type.

public class Student {


String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // gender has default value '\u0000'
}

36
The null Value

➢ If a data field of a reference type does not reference


any object, the data field holds a special literal value,
null.

37
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, and
'\u0000' for a char type. However, Java assigns no default
value to a local variable inside a method.
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " + student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
38
Default Value for a Data Field
- Example
➢ Java assigns no default value to a local variable inside a
method.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}

Compilation error: variables not


initialized 39
Differences between Variables of
Primitive Data Types and Object Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

radius = 1

40
Copying Variables of Primitive
Data Types and Object Types
Primitive type assignment i = j

Before: After:

i 1 i 2

j 2 j 2

Object type assignment c1 = c2

Before: After:

c1 c1

c2 c2

c1: Circle c2:


C2: Circle
Circle c1: Circle c2: Circle
C2: Circle
radius = 5 radius = 9 radius = 5 radius = 9 41
Encapsulation

➢ In Object-oriented programming we group related


variables and functions that operate on them into
objects and this is what we call encapsulation.
➢ Encapsulation in Java is mechanism of wrapping the data
(variables) and code acting on the data (method)
together as a single unit. In encapsulation, the meber
variable of a class will be hidden from others classes,
and can be accessed only through the methods of their
current class. Therefore, it is also know as data hiding.
➢ To achieve encapsulation in Java-
➢ Declare the variables of a class as private.
➢ Provide public setter and getter methods to modify and
view the variables values.

42
The Date Class

➢ Java provides a system-independent encapsulation of


date and time in the java.util.Date class. You can use
the Date class to create an instance for the current date
and time and use its toString method to return the date
and time as a string.

java.util.Date
The + sign indicates
public modifer +Date() Constructs a Date object for the current time.
+Date(elapseTime: long) Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String Returns a string representing the date and time.
+getTime(): long Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void Sets a new elapse time in the object.
43
The Date Class Example

➢ For example, the following code

➢ java.util.Date date = new java.util.Date();


➢ System.out.println(date.toString());

➢ Displays a string like Sun Mar 09 13:50:19 EST 2003.

44
Visibility Modifiers and
Accessor/Mutator Methods
➢ By default, the class, variable, or method can be accessed
by any class in the same package.
➢ Public

The class, data, or method is visible to any class in


any package.
➢ private

The data or methods can be accessed only by the declaring


class.

The get and set methods are used to read and


modify private properties.

45
Visibility Modifiers and
Accessor/Mutator Methods
➢ The private modifier restricts access to within a class, the default modifier
restricts access to within a package, and the public modifier enables
unrestricted access.

Package p1; Package p2;


public class CC3 {
class CC1 { public class CC2 { cannot access CC1;
… can access CC1 can access CC2;
} } }

46
Visibility Modifiers and
Accessor/Mutator Methods
➢ The private modifier restricts access to within a class, the default modifier
restricts access to within a package, and the public modifier enables
unrestricted access.

Package p1; Package p2;


public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() {} cannot access o.z; cannot access o.z;
void m2() {}
private void m3() {} can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
cannot invoke o.m3(); cannot invoke o.m3();
} }

47
Visibility Modifiers and
Accessor/Mutator Methods
➢ An object cannot access its private members, as shown
in (b).
➢ It is OK, however, if the object is declared in its own class,
as shown in (a).
public class Foo { public class Test {
private boolean x; public static void main(String[] args) {
Foo foo = new Foo();
public static void main(String[] args) { System.out.println(foo.x);
Foo foo = new Foo(); System.out.println(foo.convert(foo.x));
System.out.println(foo.x); }
System.out.println(foo.convert()); }
}

private int convert(boolean b) {


return x ? 1 : -1;
}
}
(b) This is wrong because x and convert are private in Foo.
(a) This is OK because object foo is used inside the Foo class

48
To prevent direct modifications of fields,
the fields should be declared private. This
is known as data field encapsulation

To protect data.
Data Field
Encapsulation:
To make class easy to maintain.

Data fields are get and set via public


methods, in an abstract way.

49
Example of
Data Field Encapsulation

Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.

+Circle() Constructs a default circle object.


+Circle(radius: double) Constructs a circle object with the specified radius.
+getRadius(): double Returns the radius of this circle.
+setRadius(radius: double): void Sets a new radius for this circle.
+getNumberOfObject(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.

Circle3 TestCircle3 Run

50
Passing Objects to Methods
➢ Passing by value for primitive type value (the value is passed to
the parameter)
➢ Passing by value for reference type value (the value is the
reference to the object)
Stack Pass by value (here
the value is 5)
Space required for the
printAreas method Pass by value
int times: 5 (here the value is
Circle c: reference the reference for
the object) Heap
Space required for the
main method
int n: 5 A circle
myCircle: reference object

TestPassObject Run
51
➢ Variables are introduced by typings: T x .
➢ Instance variables: the typings are in class definitions.

class C { T x; }

➢ Static variables: the typings are in class definitions and decorated


by static.

Summary class C { static T x; }

of ➢ Local variables: the typings are in statement blocks.

Variables void m() { T x; ... while ( e ) { S y; ... } ... }

➢ Parameters: the typings are in method parameter lists.

void m(T x, S y) { ... }

52
Assignment 1
(Due date 2nd Sept.)
 Define the Class of a kind of objects in our daily life (For example:
cars, chairs, etc.) with a constructor, 3~5 Data and 1~2 Methods.
 Submit a document file or a text file of the Java code, and the UML
diagram of the Class.
 Please submit your file with a filename as
“YourName_YourStudentId_Assign1”.
For example: WongUnHong_P1234567_Assign1.txt
 In your Java code, all the Data should be initialized within the
constructor. However, the implementations of the Methods are not
necessary.
 Return type should be void if nothing will be returned from a
Method.

 Note that copy of the example: Circle Class


or TV Class, is not accepted.
53
Assignment 1
(Due date 2nd Sept.)
 The UML diagram can be written using a table of a Microsoft
Word Document(.doc, .docx) or written in a text(.txt) file as
follow:
--------------------------------------------------
ClassName
--------------------------------------------------
(Data Fields)
dataName : dataType
--------------------------------------------------
(Methods)
constructor(argName : argType)
method(...) : returnType
--------------------------------------------------

54
Assignment 1
(Due date 2nd Sept.)
 For Example: WongUnHong_P1234567_Assign1.txt
--------------------------------------------------
Circle
--------------------------------------------------
x : double
y : double
radius : double
--------------------------------------------------
Circle(newRadius : double)
getAera() : double
contains(x : double, y : double) : boolean
--------------------------------------------------
public class Circle {
private double x, y;
private double radius;
public Circle(double newRadius) {
x = 0;
y = 0;
radius = newRadius;
}
public double getArea() {}
public boolean contains(double x, double y) {}
}

55

You might also like