Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

1

Object Oriented Programming


Fundamental – Part I

CS3342 Software Design


Dr. Jacky Keung
2

Objectives
• Learning the “Art” of “Abstract Thinking”
• Review OO fundamental concepts
• class, object, state, method, method invocation
• inheritance, superclass, subclass, polymorphism
• sub-classing as subtyping
Aware of abstraction and encapsulation

• Learn the UML notations to represent


class, object, interface, inheritance, class-
object relationships
3

Objects and Classes


• Object
• thing (e.g., me, you, him, her) from the real world
• It can be quantified to mean one specific item
• E.g., the microphone in LT-2
• The buttons on the control panel
• Object being a thing, is
• unique, of well-defined role.
• Class
• Represent all objects of the same kind
• E.g., human being,
• Your Bank Account : Class Account
• Your ATM Card: Class ATM_Card
• Your Student Records: Class Student
• Your Student ID Card: Class StudentIDCard
4

It is all about DATA !


Object-Oriented Programming (OO)
• OO Programming has become the standard programming
methodology for software engineers.
• OO Programming is a software programming paradigm using
“objects”, with instances of a class.
• In OO programming, you would design the program with the
data parts in mind, contextual information rather than
procedures.
• E.g Designing a smart phone…
• What kind of information/data to be stored/used?
• Photo files, music files, document files, meta data, phonebook contacts…
• Designing a calculator?
• Buttons, mathematical functions, display system etc..
6

class CalculatorApp

class Display

class Button

subclass SquareButton
class Calculator

subclass RectangleButton
7

Calculator
• Class Button
• Has attributes such as values and types
• Embedded functions
• Class Display
• Provides functions, displays calculations
• Class Calculator
• Contains class buttons (or different type of buttons, Square/Rectangle)
• Arrangements, coordination, such as an array of {Buttons}
• Class Calculator App
• Contains calculator object, which means you may have multiple
calculator instances, depends on your design.
• Main function
Objects and object classes (templates)
Template (class)

An object is an entity that has a state
and a set of operations on that state

A `software system’ entity that
represents instances of real-world and
system entities

State: a set of object attributes

Operations: provide services to other
objects (clients) which request these
services

An object class definition serves as a
template for creating objects

Declarations of the attributes and Mooncakes (objects)
services associated with an object of 8
Example Objects
• All Kings have something in common

An object
“instance”

Another object
“instance”
King Class
Let the set of all kings be called King Class

• Classes are templates for objects. They may be used to create objects.
• Multiple objects can be created from the same class.
Class
• A class is a set of related objects
Example: King Class presents a set of kings
• An object is an instance of a class
Example: King George III is an instance of King
Class, so is King Louis XVI…etc
• A class represents some useful concept that existing in
the problem/solution domains:
 Concrete entities (existing in the real world):
Example: bank accounts, circles, and products
 Abstract concepts: Example: windows
• Classes may inherit attributes and operations from
other classes
Another Example: Shoes

• A shoe has a
• Color (black, brown);
• Size (3, 8 ½ , 9½ , 14);
• Width (AAA, C, E);
• Style (stiletto heel, wingtip, moccasin, penny loafer);
• Material (leather, plastic)
• Color, size, width, style, and material all are attributes of
shoes
Shoe Class
• Shoe Class is the name of the set of all shoes

• A running shoe is an instance of Shoe Class


• A high heel shoe is another instance of Shoe class
Advantages of OO Paradigm
• Easier to maintain. Objects may be understood as
stand-alone entities.
• Reuse
• Objects are potentially reusable components.
• For some systems, there may be an obvious mapping
from real world entities to system objects.
• Example: In the real-world library, there are books,
people, etc. We can create similar objects for the
library
A bookshelf has a collection of books. program.

Object Book
- Describes the details of a book class Book
- Book Title, publisher, ISBN..etc

Object BookShelf
- Using some data structure (e.g. Array) class BookShelf
- Contains many Book objects
- i.e. [Book1][Book2][Book3]….[BookN]

Of course, you could have many bookshelves!


15

Rules to Name Classes


• Singular, informative, concrete, non-confusing, no space please!

Some Good Examples


Singular Account, Chart,
Informative Clock, Watch,
Concrete Flowchart, Photo, Video
Non-confusing Chinese language, Programming language,
Digital Clock, Analog Clock
16

Clock as a class:
Here are real objects of the Clock
Class  Beyond the class name
 Apart from the class name “Clock”, we need to tell others what
exactly is a clock in our system.
 A class is a set (or template) of objects that
 share the same class name (e.g., Clock),

 own the same set of attributes or variables, and

 share the same set of operations or functions.

 To model real world objects correctly, every attribute of the class


instance must be assigned with a concrete value at any time.
 (i.e., no null value, although it is available in Java or C++).
 How old are you? Ans: I am null. (It does not make sense!) 

 In implementation, we may further optimize our code.

17
18

UML notations of Class and Objects


Clock roundClock:
roundClock: squareClock:
squareClock:
Clock
Clock
Clock Clock
Clock
hour
hour hour
hour == 12
12 hour
hour == 55
minute
minute minute
minute == 45
45 minute
minute == 45
45

Class with Attributes Objects with Values.


19

Class Code
Class

Objects

Object instance: squareClock

Object instance: roundClock


20

Class structure
public class Clock
hour
hour and
and minutes
minutes are
are
{ the
the attributes
attributes of
of the
the
private int hour; class
class Clock
Clock
private int minute;

public Clock(int h, int m)


{
this.hour = h;
this.minute = m;
} In
In implementation,
implementation, we
we also
also
declare
declare the
the type
type to
to each
each
} attribute.
attribute.
21

State of Object
“What is the time now?”
• It is a quarter to one.
• Now, it is __12:45_______

• Every object must have exactly one state at any


time, and the object may change its state in its
lifetime.

• The current state of an object is the set of current


attribute values of the object.
• Question: How to change the state of an object?
• Modify the value. (e.g. setters, setXXX)
Class structure
public class Clock
{
private int hour;
private int minute;

public Clock(int h, int m) {


this.hour = h; This
This is
is aa method
method definition.
definition.
this.minute = m;
}
public void addMinute () {
minute = minute + 1;
if (minute == 60) {
minute = 0;
this.addHour();
} The
The method
method
}
public void addHour () {
invokes
invokes addHour
addHour of of
hour = hour + 1; the
the object
object pointed
pointed
if (hour == 24) { by
by this.
this.
hour = 0;
} “this”
“this” means
means
} this/self
this/self object.
object.
}
Pointing
Pointing to
to itself.
itself.
23

Methods of Classes
Two logical types of method

Operations
• Methods that change the value of some attribute of
an object (of its own or some other classes) e.g.
setName(String name)

Queries
• A query is a method that merely reports the value
of some attribute of an object or some
computation results without modifying the object’s
state. e.g. String getName()
24

3. Distinguishing these two usages


Methods of Classes of methods promotes better
modeling.

1.
1. Do
Do you
you feel
feel comfortable
comfortable if
if 2.
2. Do
Do you
you feel
feel comfortable
comfortable if
if
getBalance()
getBalance() isis an
an operation
operation deposit()
deposit() is query that
is aa query that
that
that may
may change
change the
the value
value of
of does
does not
not increment
increment the
the
“balance”
“balance” of
of your
your account
account?? “balance”
“balance” of
of your
your account
account??
Messages Passing / Object Calling
l Object.Method (Object-dot-method)
l Objects communicate by message passing: request from one
object to another asking the second object to execute one of its
methods.
State of Object
• Objects can be in different states.
• Example: A kettle may be full or empty, on or off,
cold or hot, and the state will change under the
influence of outside circumstances (some event or
action happens).

Example: A light switch has 2 states:


up and down (or "on" and "off")
27

State of Object
Suppose x is an integer, whose initial value is 10. : Direct
Direct effects
effects on
on
primitive data
initial value of x final value of primitive data
types
types such
such asas
x
integer,
integer, double,
double,
x = x – 10 10 0
string.
string.
x = x – 20 10 10
x = x – 30 10 20

Suppose a is a bank savings account instance,


At
At least
least one
one
whose initial balance (the state) is 25. Suppose
method
method hashas
further, we have a method call “withdraw”:
different
different effects
effects
initial state of a final state on
on different
different
of a states
states of
of the
the
a.withdraw(10) 25 15 object.
object.
a.withdraw(20) 25 5
a.withdraw(30) 25 25
28

Object Inheritance (subclass extends class)


“Super class/
Parent class”

extends extends

“Subclass/Child class”
29

Inheritance
X inherits from another class Y, if X is a
• A class
subclass of Y having additional (or modified)
attributes or methods MathematicalObject

• Y is called thesuperclass
X is called the subclass Shape Point Matrix

• Shape is called the superclass


Shape2D Shape3D

Circle is called the subclass


Ellipse Polygon Line Plane

• Multiple Inheritance: Circle Quadrilateral

Rectangle
UML
UML
notation
notation
Inheritance
To Model “is kind of” relationship.
Example:
Staff – is kind of – Person
Student – is kind of – Person
iPhone – is kind of – Phone

Parent class

Child class 1…class x


(inherited ALL the properties of their parent)
AND in addition to the NEW features.
Generalization and Inheritance
• Generalisation is implemented as inheritance in OO
programming languages

An abstract Super
class Class More general

Generalization
relationship
Sub More specific
Class

• Classes may be arranged in a class hierarchy where


one class (a super-class) is a generalisation of one or
more other classes (sub-classes)
Sub-Class vs. Super-Class
• A sub-class inherits from its super-class:
• ALL Attributes
• ALL Operations
• ALL Relationships
Super-class
• A sub-class may

• Add attributes and operations


• Add relationships
• Redefine (Override) inherited operations

Sub-classes
A Library Class Hierarchy Example

Class hierarchy captures


domain knowledge

Additional
attributes
34

Inheritance Example
In C++
class Clock {…};
class StopWatch: Clock {…};

Clock is a superclass of StopWatch;


StopWatch is a subclass of Clock
In Java
public class Clock {…}
public class StopWatch extends Clock {…}
Advantages of Inheritance
• It is an abstraction mechanism to classify entities
• It supports reuse both at the design and programming level
• It provides a mechanism to extend or refine a class: by adding
or overriding methods (or operations) and by adding attributes
• The inheritance diagram is a source of organisational
knowledge about domains and systems

Problems with inheritance


• Classes are not self-contained. They cannot be understood
without reference to their super-classes.
• The inheritance graphs of analysis, design and
implementation have different functions and need to
separately maintained.
36

Using Inheritance
• Inheritance (generalization) represent the is-a relationships
between classes of objects.

• For instance, a "fruit" is a generalization of "apple", "orange", "mango" and many others.
One can consider fruit to be an abstraction of apple, since apples are fruit (i.e., an apple is-
a fruit), apples may naturally inherit all the properties common to all fruit.

Given object Apple or Orange is a-type-of Fruit:

Java Valid Statement Example 1:


Fruit food = new Fruit();

Java Valid Statement Example 2:


Fruit food = new Apple(); or Fruit food = new Orange();

(Assigning an Apple object as a Fruit Object, because an Apple is a-kind-of Fruit! )

• Inheritance helps reuse existing code with little or no modification.


• An important concept in Software Engineering Design and Implementation!
37

Software Design Strategy


- Information Hiding
(Encapsulation)

Private vs Public
Information Hiding in OO (1)
• Information hiding enhances maintainability because
implementation details are invisible outside an object
• Example: class BankAccount

• Attribute accountBalance can be implemented in


many different ways:
• int - As an integer (the total amount in cents); or

• double - As a dollar amount with two decimal places for the cents

• With information hiding, these details are can be


invisible outside the object!
• OO languages allow an attribute to be described as
private (invisible outside the object)
• (-) minus-sign : private, (+) plus-sign : public
Information Hiding (2)
• Suppose that the 2 operations of Bank Account Class are
deposit and withdraw

• A private (-) attribute can be


accessed only from inside
the class in which it is
declared
• A public (+) attribute can be
accessed from anywhere in
the system

• The only way to change the variable accountBalance in


BankAccount object is to invoke functions deposit(amt
double) or withdraw(amt double).
Benefits of Information Hiding
• When we change the way accountBalance is
implemented
• If we have information hiding, this change cannot
affect any other part of the system

• With information hiding


A system consists of essentially independent classes
They communicate by sending messages
Objects do talking to each other!

You might also like