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

OOP2024 JavaSlides W5 OOP-Abstraction

The document discusses abstraction in object-oriented programming. Abstraction allows hiding unnecessary details and showing only essential attributes, reducing complexity. It can be achieved through abstract classes and interfaces. Abstract classes define abstract methods that subclasses must implement, while interfaces contain only abstract method signatures.

Uploaded by

Trang Lò Thị
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

OOP2024 JavaSlides W5 OOP-Abstraction

The document discusses abstraction in object-oriented programming. Abstraction allows hiding unnecessary details and showing only essential attributes, reducing complexity. It can be achieved through abstract classes and interfaces. Abstract classes define abstract methods that subclasses must implement, while interfaces contain only abstract method signatures.

Uploaded by

Trang Lò Thị
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

Object-Oriented Programming

Using Java
Abstraction

Quan Thai Ha

HUS
February 18, 2024
Presentation Outline

1 Abstraction
Abstract Classes
Interfaces
Usage of abstract classes
Usage of interfaces

2 Abstract Data Types

3 Modelling Tools and Languages

4 References

1 105
Abstraction

Abstraction is the concept of object-oriented programming that shows only essential


attributes and hides unnecessary information.
The main purpose of abstraction is hiding the unnecessary details from the users
(information hiding).
Abstraction is selecting data from a larger pool to show only relevant details of the object
to the user. It helps in reducing programming complexity and efforts.
You can take a real-life example. On a laptop you can see
the screen, use the keyboard and type something, you can
use the mouse pad and can do all your work on the laptop.
But do you know its internal details, how that keys are
working and how the motherboard of the laptop is
working, and how the picture is showing up on the screen?
So here, all the internal implementation of the laptop is
hidden from the user and it is separated from its external
interface. You can use the laptop without knowing its
internal implementation. So abstraction provides simple
and easy-to-use interfaces for the user.
2 105
Abstraction with Interfaces

3 105
Abstraction with Abstract Classes

4 105
Abstraction with Interfaces and Abstract Classes

5 105
Example of Designing a Java Project

6 105
How is Abstraction Created?

Suppose that our program uses many kinds of


computers, such as MacbookPro, MacbookAir,
and so on. The method powerOn() has been
written in all of the classes and has
functionality to start computer.
Implementation of the method powerOn() in
the AppleComputer is NOT possible, as the
actual computer is not yet known. It has been
tagged as abstract. Implementation of these
abstract method will be provided later once
the actual computer is known. These abstract
methods cannot be invoked because they have
no implementation.
A class containing one or more abstract
methods is called an abstract class. An The Abstraction hides detailed information on
abstract class CANNOT be instantiated, as its how to start the computer.
definition is not complete.

7 105
How is Abstraction Created?

If we required we could also tag the


powerOn() method as abstract in a
derived class, for example we could also
have tagged the powerOn() as abstract
in the Laptop class.
This would mean that you could not
create an object of the Laptop class.
It would pass on responsibility for
implementing the powerOn() method
to its children.

8 105
Information Hiding

Information hiding is like walls


building around the various classes of a
program.
The wall around each class T prevents
the other classes from seeing how T
works.
Thus, if class Q uses (depends on) T,
and if the approach for performing T
changes, class Q will not be affected.
Makes it easy to substitute new,
improved versions of how to do a task
later.

9 105
Meaning of Abstraction

Abstraction can be achieved in two different way:


▶ Using abstract classes
▶ Using interfaces

10 105
Presentation Outline

1 Abstraction
Abstract Classes
Interfaces
Usage of abstract classes
Usage of interfaces

2 Abstract Data Types

3 Modelling Tools and Languages

4 References

11 105
Abstract methods

An abstract method is a method with only signature (i.e., the method name, the list of
arguments and the return type) without implementation (i.e., the method’s body). You use
the keyword abstract to declare an abstract method.
These abstract methods cannot be invoked because they have no implementation.
Example

Implementation of these methods is


1 p u b l i c a b s t r a c t c l a s s Shape {
NOT possible in the Shape class, as
...... the actual shape is not yet known.
3 ...... (How to compute the area if the
5 p u b l i c abstract d o u b l e g e t A r e a ( ) ; shape is not known?) Implementation
p u b l i c abstract d o u b l e g e t P e r i m e t e r ( ) ; of these abstract methods will be
7 p u b l i c abstract v o i d draw ( ) ;
} provided later once the actual shape
is known.

12 105
Abstract classes
A class containing one or more abstract methods is called an abstract class. An abstract
class must be declared with a class-modifier abstract.
An abstract class is incomplete in its definition, since the implementation of its abstract
methods is missing. Therefore, an abstract class cannot be instantiated. In other words,
you cannot create instances from an abstract class (otherwise, you will have an incomplete
instance with missing method’s body).
Example

You can create instances of the


p u b l i c abstract c l a s s Shape { subclasses such as Triangle and
2 ...... Rectangle, and upcast them to Shape
......
4 p u b l i c abstract d o u b l e g e t A r e a ( ) ;
(so as to program and operate at the
p u b l i c abstract d o u b l e g e t P e r i m e t e r ( ) ; interface level), but you cannot create
6 p u b l i c abstract v o i d draw ( ) ; instance of Shape.
}

13 105
Example of the abstract class

1 /∗ ∗
∗ T h i s a b s t r a c t s u p e r c l a s s Shape c o n t a i n s an a b s t r a c t method
3 ∗ g e t A r e a ( ) , t o be implemented by i t s s u b c l a s s e s .
∗/
5 p u b l i c abstract c l a s s Shape {
private String color ;
7
p u b l i c Shape ( S t r i n g c o l o r ) {
9 this . color = color ;
}
11
@Override
13 public String toString () {
r e t u r n " Shape [ c o l o r = " + c o l o r + " ] " ;
15 }

17 / / A l l Shape ’ s c o n c r e t e s u b c l a s s e s must implement a method c a l l e d g e t A r e a ( )


p u b l i c abstract d o u b l e g e t A r e a ( ) ;
19 }

14 105
Usage of Abstract Classes
To use an abstract class, you have to derive a subclass from the abstract class. In the
derived subclass, you have to override the abstract methods and provide implementation to
all the abstract methods. The subclass derived is now complete, and can be instantiated. (If
a subclass does not provide implementation to all the abstract methods of the superclass,
the subclass remains abstract.)

For example, in the abstract class


1 p u b l i c c l a s s R e c t a n g l e e x t e n d s Shape {
Shape, you can define abstract
private int length ; methods such as getArea(). No
3 p r i v a t e i n t w i d th ; implementation is possible because
5 public Rectangle ( . . . ) { ... } the actual shape is not known.
However, by specifying the signature
7 @Override
public double getArea() { of the abstract methods, all the
9 r e t u r n l e n g t h ∗ w i d th ; subclasses are forced to use these
}
11 }
methods’ signature. The subclasses
Rectangle could provide the proper
implementations.
15 105
Usage of Abstract Classes
In summary, an abstract class provides a template for further development. The purpose of
an abstract class is to provide a common interface (or protocol, or contract, or
understanding, or naming convention) to all its subclasses.
Coupled with polymorphism, you can upcast subclass instances to Shape, and program at
the Shape level, i.e., program at the interface. The separation of interface and
implementation enables better software design, and ease in expansion.
▶ For example, Shape defines a method called getArea(), which all the subclasses must provide
the correct implementation. You can ask for a getArea() from any subclasses of Shape, the
correct area will be computed.
▶ Furthermore, your application can be extended easily to accommodate new shapes (such as
Circle or Square) by deriving more subclasses.
Notes
▶ An abstract method cannot be declared final, as final method cannot be overridden. An
abstract method, on the other hand, must be overridden in a descendant before it can be used.
▶ An abstract method cannot be private (which generates a compilation error). This is because
private method are not visible to the subclass and thus cannot be overridden.
16 105
Example of Usage of Abstract Classes
Rule of Thumb: Program at the interface, not at the implementation. (That is, make
references at the superclass; substitute with subclass instances; and invoke methods
defined in the superclass only.)

1 p u b l i c c l a s s TestShape {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 Shape s 1 = new R e c t a n g l e ( " r e d " , 4 , 5 ) ;
System . o u t . p r i n t l n ( s 1 ) ;
5 System . o u t . p r i n t l n ( " Area i s " + s 1 . g e t A r e a ( ) ) ;

7 Shape s 2 = new T r i a n g l e ( " b l u e " , 4 , 5 ) ;


System . o u t . p r i n t l n ( s 2 ) ;
9 System . o u t . p r i n t l n ( " Area i s " + s 2 . g e t A r e a ( ) ) ;

11 / / Cannot c r e a t e i n s t a n c e o f an a b s t r a c t c l a s s
Shape s3 = new Shape("green");
13 / / Compilation error: Shape is abstract; cannot be instantiated.
}
15 }

17 105
Presentation Outline

1 Abstraction
Abstract Classes
Interfaces
Usage of abstract classes
Usage of interfaces

2 Abstract Data Types

3 Modelling Tools and Languages

4 References

18 105
Interfaces

A Java interface is a 100% abstract superclass which define a set of methods its subclasses
must support.
An interface contains only public abstract methods (methods with signature and no
implementation) and possibly constants (public static final variables).
You have to use the keyword "interface" to define an interface (instead of keyword "class"
for normal classes).
The keyword public and abstract are not needed for its abstract methods as they are
mandatory.
Unlike a normal class, where you use the keyword "extends" to derive a subclass. For
interface, we use the keyword "implements" to derive a subclass.
Interface Naming Convention: Use an adjective (typically ends with "able") consisting of
one or more words. Each word shall be initial capitalized (camel-case).
▶ For example, Serializable, Extenalizable, Movable, Clonable, Runnable, etc.

19 105
Defines Interface

1 /∗ ∗
∗ The Movable i n t e r f a c e d e f i n e s a l i s t o f p u b l i c a b s t r a c t methods
3 ∗ t o be implemented by i t s s u b c l a s s e s
∗/
5 p u b l i c i n t e r f a c e Movable { / / Use keyword " i n t e r f a c e " ( instead of " c l a s s " ) to
// d e f i n e an interface
7 / / An i n t e r f a c e d e f i n e s a l i s t o f p u b l i c a b s t r a c t methods t o be implemented
// by t h e s u b c l a s s e s
9 [public abstract] v o i d moveUp ( ) ; // " public " and " a b s t r a c t " o p t i o n a l
v o i d moveDown ( ) ;
11 void moveLeft ( ) ;
v o i d moveRight ( ) ;
13 }

20 105
Implements interface

1 /∗ ∗
∗ The s u b c l a s s M o v a b l e P o i n t n e e d s t o
3 ∗ implement a l l t h e a b s t r a c t methods
∗ d e f i n e d i n t h e i n t e r f a c e Movable .
5 ∗/
/ / U s i n g keyword implements i n s t e a d o f extends
7 p u b l i c c l a s s M o v a b l e P o i n t implements Movable {
private int x ;
9 private int y ;

11 p u b l i c MovablePoint ( i n t x , i n t y ) { ... }

13 @Override
p u b l i c v o i d moveUp ( ) {
15 y − −;
}
17
@Override
19 p u b l i c v o i d moveDown ( ) {
y ++;
21 }
...
23 }

21 105
Usage of interface

1 p u b l i c c l a s s TestMovable {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 M o v a b l e P o i n t p1 = new M o v a b l e P o i n t ( 1 , 2 ) ;
System . o u t . p r i n t l n ( p1 ) ; // (1 ,2)
5 p1 . moveDown ( ) ;
System . o u t . p r i n t l n ( p1 ) ; // (1 ,3)
7 p1 . moveRight ( ) ;
System . o u t . p r i n t l n ( p1 ) ; // (2 ,3)
9
/ / Usage o f i n t e r f a c e .
11 Movable p2 = new M o v a b l e P o i n t ( 3 , 4 ) ; / / Upcast . I n t e r f a c e as a datatype .
p2 . moveUp ( ) ; / / T e s t polymorphism .
13 System . o u t . p r i n t l n ( p2 ) ; // (3 ,3)

15 M o v a b l e P o i n t p3 = ( M o v a b l e P o i n t ) p2 ; / / Downcast
System . o u t . p r i n t l n ( p3 ) ; // (3 ,3)
17 }
}

22 105
Why interfaces?

An interface is a contract for what the classes can do. It, however, does not specify how the
classes should do it.
An interface provides a form, a protocol, a standard, a contract, a specification, a set of
rules, an interface, for all objects that implement it. It is a specification and rules that any
object implementing it agrees to follow.
Similar to an abstract superclass, an interface cannot be instantiated. You have to create a
"subclass" that implements an interface, and provide the actual implementation of all the
abstract methods.
In Java, abstract class and interface are used to separate the public interface of a class from
its implementation so as to allow the programmer to program at the interface instead of
the various implementation.

23 105
Why interfaces?

One of the main usage of interface is provide a communication contract between two
objects. If you know a class implements an interface, then you know that class contains
concrete implementations of the methods declared in that interface, and you are
guaranteed to be able to invoke these methods safely. In other words, two objects can
communicate based on the contract defined in the interface, instead of their specific
implementation.
Secondly, Java does not support multiple inheritance (whereas C++ does). Multiple
inheritance permits you to derive a subclass from more than one direct superclass. This
poses a problem if two direct superclasses have conflicting implementations. (Which one
to follow in the subclass?). However, multiple inheritance does have its place. Java does
this by permitting you to "implements" more than one interfaces (but you can only
"extends" from a single superclass). Since interfaces contain only abstract methods without
actual implementation, no conflict can arise among the multiple interfaces. (Interface can
hold constants but is not recommended. If a subclass implements two interfaces with
conflicting constants, the compiler will flag out a compilation error.)

24 105
Summary

An abstract class is a class that is incomplete in the sense it has missing method bodies. In
that it describes a set of operations, but is missing the actual implementation of these
operations.
A class is like a set of plans from which you can create objects. In relation to this analogy,
an abstract class is like a set of plans with some part of the plans missing. E.g. it could be a
car with no engine - you would not be able to make complete car objects without the
missing parts of the plan.

25 105
Summary
Any class containing one or more abstract methods is an abstract class.
You must declare the class with the keyword abstract:

a b s t r a c t c l a s s MyClass { ... }

You cannot instantiate (create a new instance of) an abstract class.


▶ So, can only be used through inheritance.
You can extend (subclass) an abstract class.
▶ If the subclass defines all the inherited abstract methods, it is concrete and can be instantiated.
▶ If the subclass does not define all the inherited abstract methods, it must be abstract too.

You can declare a class to be abstract even if it does not contain any abstract methods.
▶ This just prevents the class from being instantiated.

26 105
Presentation Outline

1 Abstraction
Abstract Classes
Interfaces
Usage of abstract classes
Usage of interfaces

2 Abstract Data Types

3 Modelling Tools and Languages

4 References

27 105
Why abstract classes?

Suppose you wanted to create a class


Shape, with subclasses Oval, Rectangle,
Triangle, Hexagon, etc. c l a s s Shape { ... }
2

Each subclass implements a method c l a s s S t a r e x t e n d s Shape {


4 v o i d draw ( ) { . . . }
draw() for representing its shape on a 2D ...
graphic panel. 6 }

8 c l a s s C i r c l e e x t e n d s Shape {
v o i d draw ( ) { . . . }
10 ...
}

28 105
A Problem

c l a s s Shape { ... } / / L e g a l , b u t unwanted


2 2 Shape s h ap e = new Shape ( ) ;
c l a s s S t a r e x t e n d s Shape { / / I l l e g a l , Shape d o e s n o t have draw ( )
4 v o i d draw ( ) { . . . } 4 s ha p e . draw ( ) ;
... / / L e g a l , b e c a u s e a S t a r i s a Shape
6 } 6 s ha p e = new S t a r ( ) ;
/ / I l l e g a l , Shape d o e s n o t have draw ( )
8 c l a s s C i r c l e e x t e n d s Shape { 8 s ha p e . draw ( ) ;
v o i d draw ( ) { . . . }
10 ... 10 / / Same problem , a n o t h e r v i e w
} Shape [ ] s h a p e s = new Shape [ 1 6 ] ;
12 s h a p e s [ 0 ] = new C i r c l e ( ) ;
s h a p e s [ 1 ] = new S t a r ( ) ;
14 ...

16 f o r ( Shape s : s h a p e s ) {
/ / I l l e g a l , Shape doesn ’ t have draw ( )
18 s . draw ( ) ;
}

29 105
A Solution

c l a s s Shape {
2 void draw() { ... }
}
4
c l a s s S t a r e x t e n d s Shape {
6 void draw() { ... }
...
8 }

10 c l a s s C i r c l e e x t e n d s Shape {
void draw() { ... }
12 ...
}
14
Shape s h ap e ;
16 s ha p e = new Shape ( ) ; // Legal, but unwanted, because Shape does not need to exist in reality.
s ha p e . draw ( ) ; // Legal, but unwanted, because Shape has no specific shape.
18 s ha p e = new S t a r ( ) ; // L e g a l , b e c a u s e a S t a r i s a Shape .
s ha p e . draw ( ) ; // L e g a l , Shape d o e s have draw ( ) .

30 105
A Better Solution

1 abstract c l a s s Shape {
abstract void draw();
3 }

5 c l a s s S t a r e x t e n d s Shape {
void draw() { ... }
7 ...
}
9
c l a s s C i r c l e e x t e n d s Shape {
11 void draw() { ... }
...
13 }

15 Shape s h ap e ;
shape = new Shape(); / / Illegal, Shape is abstract.
17 s ha p e = new S t a r ( ) ; / / L e g a l , b e c a u s e a S t a r i s a Shape .
s ha p e . draw ( ) ; / / L e g a l , Shape d o e s have draw ( ) .

31 105
Another problem

Let’s suppose that all shapes must have two


capabilities:
a b s t r a c t c l a s s Shape {
▶ Drawing their own shape (draw() method). 2 void setId ( ) { . . . } ;
▶ Storing an unique Id (setId() method). a b s t r a c t v o i d draw ( ) ;
4 }
We can keep the draw() method abstract
6 c l a s s S t a r e x t e n d s Shape {
while providing an implementation of the v o i d draw ( ) { . . . }
setId() method. In this way, Shape cannot be 8 ...
}
instantiated and Shape subclasses can 10
implement draw(). c l a s s C i r c l e e x t e n d s Shape {
12 v o i d draw ( ) { . . . }
Benefit: repeated code minimized! ...
14 }
Drawback: completely abstract concepts are
missing!

32 105
Presentation Outline

1 Abstraction
Abstract Classes
Interfaces
Usage of abstract classes
Usage of interfaces

2 Abstract Data Types

3 Modelling Tools and Languages

4 References

33 105
Interfaces

Completely abstract concepts can be defined


by making use of Interfaces.
1 interface Shape {
Interfaces are particular classes containing public abstract v o i d s e t I d ( ) ;
exclusively abstract methods. All their 3 public abstract v o i d draw ( ) ;
}
methods are implicitly public and abstract. 5
Thus, Interfaces cannot be instantiated. c l a s s S t a r implements Shape {
7 void setId ( ) { . . . }
When a class implements an interface, it v o i d draw ( ) { . . . }
9 ...
promises to the compiler to provide an }
implementation for all the methods declared 11
c l a s s C i r c l e implements Shape {
within the interface. 13 void setId ( ) { . . . }
v o i d draw ( ) { . . . }
Benefit: completely abstract concepts! 15 ...
}
Drawback: repeated code possible!

34 105
Interfaces

Interfaces can be specialized.


Specializing an interface means adding new methods in derived interfaces. Overriding
methods does not make sense in interfaces because code is absent.

1 i n t e r f a c e Shape {
public abstract v o i d s e t I d ( ) ;
3 public abstract v o i d draw ( ) ;
}
5
i n t e r f a c e MovingShape e x t e n d s Shape {
7 public abstract v o i d move ( P o i n t p ) ;
}

35 105
Interfaces

Interfaces can be partially implemented


in abstract classes. The approach
provides both abstract concepts and i n t e r f a c e Shape {
public abstract v o i d s e t I d ( ) ;
reduced code repetition. 2
public abstract v o i d draw ( ) ;
4 }
Widely used inside the Java API.
6 a b s t r a c t c l a s s A b s t r a c t S h a p e implements Shape {
void setId ( ) { . . . } ;
8 a b s t r a c t v o i d draw ( ) ;
}
10
c l a s s S t a r extends A b s t r a c t S h a p e {
12 v o i d draw ( ) { . . . }
...
14 }

16 c l a s s C i r c l e extends A b s t r a c t S h a p e {
v o i d draw ( ) { . . . }
18 ...
}

36 105
Default methods

In a typical design based on


abstractions, where an interface has
one or multiple implementations, if 1 p u b l i c i n t e r f a c e Shape {
void setId ( ) ;
one or more methods are added to an 3 v o i d draw ( ) ;
interface, all the implementations will
5 default String getDescription() {
be forced to implement them too. return "This is a Shape.";
7 }
Default interface methods are an }
efficient way to deal with this issue. 9
p u b l i c c l a s s C i r c l e i m p l e m e n t s Shape {
They allow us to add new methods to 11 void setId ( ) { . . . }
v o i d draw ( ) { . . . }
an interface that are automatically 13 ...
available in the implementations. }
Therefore, we don’t need to modify 15

the implementing classes. 17 C i r c l e c i r c l e = new C i r c l e ( ) ;


c i r c l e . getDescription () ;

37 105
Static methods

In addition to declaring default methods


in interfaces, Java also allows us to define
and implement static methods in i n t e r f a c e Shape {
2 void setID ( ) ;
interfaces. v o i d draw ( ) ;
4
Since static methods don’t belong to a public static String getDescription() {
particular object, they’re not part of the 6 return "This is a Shape";
}
API of the classes implementing the 8 }
interface, therefore, they have to
10 c l a s s C i r c l e i m p l e m e n t s Shape {
be called by using the interface name void setId ( ) { . . . }
preceding the method name. 12 v o i d draw ( ) { . . . }
...
14 }

16
Shape . g e t D e s c r i p t i o n ( ) ;

38 105
Multiple inheritance

In Java, a class can only extend one class, but can implement multiple interfaces. This lets
the class fill multiple roles (i.e., multiple set of methods).
▶ Collections (e.g., LinkedList) commonly implement multiple interfaces.
▶ Graphical containers (e.g., JFrame) commonly implement several listeners (i.e., interfaces).

c l a s s L i n k e d L i s t e x t e n d s A b s t r a c t L i s t i m p l e m e n t s L i s t , Queue {
2 ...
}
4
c l a s s A p p l i c a t i o n e x t e n d s JFrame i m p l e m e n t s A c t i o n L i s t e n e r , K e y L i s t e n e r {
6 ...
}

39 105
Multiple inheritance

1 p u b l i c class G r o u d V e h i c l e {
public activateWheels ( ) {
3 ...
}
5 }

7 p u b l i c class W a t e r V e h i c l e {
public activateWaterFans ( ) {
9 ...
}
11 }

13
/ / Not allowed in Java‼ Only one class can be extended!
15 p u b l i c class A n p h i b i a n extends G r o u d V e h i c l e , W a t e r V e h i c l e {
...
17 }

40 105
Multiple inheritance

1 p u b l i c interface G r o u d V e h i c l e {
activateWheels ( ) ;
3 }

5 p u b l i c interface W a t e r V e h i c l e {
activateWaterFans ( ) ;
7 }

9
p u b l i c class A n p h i b i a n implements G r o u d V e h i c l e , W a t e r V e h i c l e {
11 activateWheels ( ) {
...
13 }

15 activateWaterFans ( ) {
...
17 }
}

41 105
Interfaces and instanceof

instanceof is an operator telling whether an object "IS-A" member of a class of objects.


Membership practically means having its methods implemented.

c l a s s Dog e x t e n d s Mammal i m p l e m e n t s Pet , F r i e n d , Fun {


2 ...
}
4
Dog l e s s i e = new Dog ( ) ;
6 l e s s i e instan ceof Object // OK !
l e s s i e i n s t a n c e o f Dog // OK !
8 l e s s i e i n s t a n c e o f Mammal // OK !
l e s s i e i n s t a n c e o f Pet // OK !
10 l e s s i e instanceof Friend // OK !

42 105
Presentation Outline

1 Abstraction

2 Abstract Data Types


Complex Number
List

3 Modelling Tools and Languages

4 References

43 105
Program Design Principles

Abstraction
▶ Concentrate on what it CAN DO and NOT how it does it.
▶ E.g. usage of Abstract Class and Interface.

Coupling
▶ Restrict interdependent relationship among classes to the minimum.

Cohesion
▶ A class should be about a single entity only.
▶ There should be a clear logical grouping of all functionalities.

Information Hiding
▶ Expose only necessary information to outside.

44 105
Information Hiding

Information hiding is like walls


building around the various classes of a
program.
The wall around each class T prevents
the other classes from seeing how T
works.
Thus, if class Q uses (depends on) T,
and if the approach for performing T
changes, class Q will not be affected.
Makes it easy to substitute new,
improved versions of how to do a task
later.

45 105
Information Hiding

Information Hiding is not complete isolation of the classes.


Information released is on a need-to-know basis.
Class Q does not know how class T does the work, but it needs to know how to invoke T
and what T produces.
- E.g.: The designers of the methods of Math and Scanner classes have hidden the details of the
implementations of the methods from you, but provide enough information (the method
headers and explanation) to allow you to use their methods.
What goes in and comes out is governed by the terms of the method’s specifications.
- If you use this method in this way, this is exactly what it will do for you (pre- and
post-conditions).

46 105
Pre- and post-conditions

Pre-conditions
▶ Conditions that must be true before a method is called.
▶ "This is what I expect from you".
▶ The programmer is responsible for making sure that the pre-conditions are satisfied when
calling the method.
Post-conditions
▶ Conditions that must be true after the method is completed.
▶ "This is what I promise to do for you".

/ / Pre − cond : x >= 0


2 / / P o s t − cond : R e t u r n t h e s q u a r e r o o t o f x
p u b l i c s t a t i c double squareRoot ( double x ) {
4 . . .
}

47 105
Information Hiding

Information Hiding can also apply to data.


▶ Data abstraction asks that you think in terms of what you can do to a collection of data
independently of how you do it.
▶ Data structure is a construct that can be defined within a programming language to store a
collection of data.
▶ Abstract Data Type (ADT) is a collection of data and a specification on the set of
operations/methods on that data.
- Typical operations on data are: add, remove, and query (in general, management of data).
- Specification indicates what ADT operations do, but not how to implement them.

48 105
Data Structure
Data structure is a construct that can be defined within a programming language to store a
collection of data.
▶ Arrays, which are built into Java, are data structures.
▶ We can create other data structures. For example, we want a data structure (a collection of
data) to store both the names and salaries of a collection of employees.

1 s t a t i c f i n a l i n t MAX_NUMBER = 5 0 0 ; / / defining a constant


S t r i n g [ ] names = new S t r i n g [MAX_NUMBER ] ;
3 d o u b l e [ ] s a l a r i e s = new d o u b l e [MAX_NUMBER ] ;
/ / employee names [ i ] has a s a l a r y o f s a l a r i e s [ i ]
5
/ / Or ( b e t t e r c h o i c e )
7
c l a s s Employee {
9 s t a t i c f i n a l i n t MAX_NUMBER = 5 0 0 ;
p r i v a t e S t r i n g names ;
11 p r i v a t e double s a l a r i e s ;
}
13 . . .
Employee [ ] w o r k e r s = new Employee [ Employee . MAX_NUMBER ] ;

49 105
Abstract Data Type

An ADT is a collection of data together with a specification of a set of operations on the


data.
▶ Specifications indicate what ADT operations do, NOT how to implement them.
▶ Data structures are part of an ADT’s implementation.

When a program needs data operations that are not directly supported by a language, you
need to create your own ADT.
You should first design the ADT by carefully specifying the operations before
implementation.
50 105
Abstract Data Type

A WALL of ADT operations isolates a data structure from the program that uses it.
An Interface is what a program/module/class should understand on using the ADT.

51 105
Abstract Data Type

An interface is what a program/module/class should understand on using the ADT.


The following bypasses the interface to access the data structure. This violates the wall of
ADT operations.

52 105
Primitive Types as ADTs

Java’s predefined data types are ADTs.


Representation details are hidden which aids portability as well.

53 105
Arrays as ADTs
Constructors (to add, create data)

i n t [ ] z = new i n t [ 4 ] ;
2 int [] x = {2 ,4 ,6 ,8};

Mutators (to modify data)

x [3] = 10;

Accessors (to query about state/value of data)

1 int y = x [3] + x [ 2 ];

54 105
Presentation Outline

1 Abstraction

2 Abstract Data Types


Complex Number
List

3 Modelling Tools and Languages

4 References

55 105
Complex Number as ADT

A complex number comprises a real part a and an imaginary part b, and is written as a + bi.
i is a value such that i2 = −1.
Examples: 12 + 3i, 15 − 9i, −5 + 4i, −23, 18i.

A complex number can


be visually represented as
a pair of numbers (a, b)
representing a vector on
the two-dimensional
complex plane
(horizontal axis for real
part, vertical axis for
imaginary part).

56 105
Designing complex number
Interface

Implementation: two different ways

1 c l a s s CartesianComplex { c l a s s PolarComplex {
p r i v a t e double r e a l ; 2 p r i v a t e d o u b l e ang ;
3 p r i v a t e d o u b l e imag ; p r i v a t e d o u b l e mag ;
} 4 }

57 105
Designing complex number

Relationship between Cartesian and Polar representations

From Polar to Cartesian: From Polar to Cartesian:


real = modulus ∗ cos(argument); argument = tan−1 (imag/real);
imag = modulus ∗ sin(argument); modulus = real/ cos(argument);
or modulus = sqrt(real2 + imag 2 );

58 105
Complex Number Implementation without Abstraction

c l a s s CartesianComplex {
2 p r i v a t e double r e a l ;
p r i v a t e d o u b l e imag ;
4
p u b l i c Complex ( d o u b l e r e a l , d o u b l e imag ) {
6 this . real = real ;
t h i s . imag = imag ;
8 }

10 p u b l i c double r e a l P a r t ( ) {
return real ;
12 }

14 p u b l i c double imagPart ( ) {
r e t u r n imag ;
16 }

59 105
Complex Number Implementation without Abstraction

p u b l i c d o u b l e modulus ( ) {
2 r e t u r n Math . s q r t ( r e a l ∗ r e a l + imag ∗ imag ) ;
}
4
p u b l i c d o u b l e argument ( ) {
6 i f ( real != 0) {
i f ( real < 0) {
8 r e t u r n ( Math . P I + Math . a t a n ( imag / r e a l ) ) ;
} else {
10 r e t u r n Math . a t a n ( imag / r e a l ) ;
}
12 } e l s e i f ( imag == 0 ) {
return 0;
14 } e l s e i f ( imag > 0 ) {
r e t u r n Math . P I / 2 ;
16 } else {
r e t u r n −Math . P I / 2 ;
18 }
}

60 105
Complex Number Implementation without Abstraction

1 p u b l i c v o i d add ( C a r t e s i a n C o m p l e x c ) {
r e a l += c . r e a l P a r t ( ) ;
3 imag += c . i m a g P a r t ( ) ;
}
5
p u b l i c v o i d minus ( C a r t e s i a n C o m p l e x c ) {
7 r e a l −= c . r e a l P a r t ( ) ;
imag −= c . i m a g P a r t ( ) ;
9 }

11 p u b l i c void times ( CartesianComplex c ) {


r e a l = r e a l ∗ c . r e a l P a r t ( ) − imag ∗ c . i m a g P a r t ( ) ;
13 imag = r e a l ∗ c . i m a g P a r t ( ) + imag ∗ c . r e a l P a r t ( ) ;
}
15
public String toString () {
17 i f ( imag == 0 ) { r e t u r n ( r e a l + " " ) ;
i f ( imag < 0 ) r e t u r n ( r e a l + " − " + imag + " i " ) ;
19 r e t u r n ( r e a l + " + " + imag + " i " ) ;
}
21 }

61 105
Complex Number Implementation without Abstraction

1 c l a s s PolarComplex {
p r i v a t e d o u b l e modulus ;
3 p r i v a t e d o u b l e argument ;

5 p u b l i c Complex ( d o u b l e modulus , d o u b l e argument ) {


t h i s . modulus = modulus ;
7 t h i s . argument = argument ;
}
9
p u b l i c double r e a l P a r t ( ) {
11 r e t u r n modulus ∗ Math . c o s ( argument ) ;
}
13
p u b l i c double imagPart ( ) {
15 r e t u r n modulus ∗ Math . s i n ( argument ) ;
}

62 105
Complex Number Implementation without Abstraction

p u b l i c v o i d add ( P o l a r C o m p l e x c ) {
2 double r e a l = t h i s . r e a l P a r t ( ) + c . r e a l P a r t ( ) ;
d o u b l e imag = t h i s . i m a g P a r t ( ) + c . i m a g P a r t ( ) ;
4
modulus = Math . s q r t ( r e a l ∗ r e a l + imag ∗ imag ) ;
6 i f ( real != 0) {
i f ( real < 0) {
8 argument = ( Math . P I + Math . a t a n ( imag / r e a l ) ) ;
} else {
10 argument = Math . a t a n ( imag / r e a l ) ;
}
12 } e l s e i f ( imag == 0 ) {
argument = 0 ;
14 } e l s e i f ( imag > 0 ) {
argument = Math . P I / 2 ;
16 } else {
argument = −Math . P I / 2 ;
18 }
}

63 105
Complex Number Implementation without Abstraction

1 p u b l i c v o i d minus ( P o l a r C o m p l e x c ) {
d o u b l e r e a l = mag ∗ Math . c o s ( ang ) − c . r e a l P a r t ( ) ;
3 d o u b l e imag = mag ∗ Math . s i n ( ang ) − c . i m a g P a r t ( ) ;

5 modulus = Math . s q r t ( r e a l ∗ r e a l + imag ∗ imag ) ;


i f ( real != 0) {
7 i f ( real < 0) {
argument = ( Math . P I + Math . a t a n ( imag / r e a l ) ) ;
9 } else {
argument = Math . a t a n ( imag / r e a l ) ;
11 }
} e l s e i f ( imag == 0 ) {
13 argument = 0 ;
} e l s e i f ( imag > 0 ) {
15 argument = Math . P I / 2 ;
} else {
17 argument = −Math . P I / 2 ;
}
19 }

64 105
Complex Number Implementation without Abstraction

1 p u b l i c d o u b l e modulus ( ) {
r e t u r n t h i s . modulus ;
3 }

5 p u b l i c d o u b l e argument ( ) {
r e t u r n t h i s . argument ;
7 }

9 p u b l i c void times ( PolarComplex c ) {


modulus ∗ = c . modulus ( ) ;
11 argument += c . argument ( ) ;
}
13
public String toString () {
15 i f ( i m a g P a r t ( ) == 0 ) r e t u r n ( r e a l p a r t ( ) + " " ) ;
i f ( imagPart ( ) < 0) return ( r e a l P a r t ( ) + " − " + imagPart ( ) + " i " ) ;
17 return ( r e a l P a r t ( ) + " + " + imagPart ( ) + " i " ) ;
}
19 }

65 105
Complex Number Implementation without Abstraction

1 / / Testing CartesianComplex
C a r t e s i a n C o m p l e x a = new C a r t e s i a n C o m p l e x ( 1 0 . 0 , 1 2 . 0 ) ;
3 C a r t e s i a n C o m p l e x b = new C a r t e s i a n C o m p l e x ( 1 . 0 , 2 . 0 ) ;
a . add ( b ) ;
5 System . o u t . p r i n t l n ( " a = a + b i s " + a ) ;
a . minus ( b ) ;
7 System . o u t . p r i n t l n ( " a − b ( which i s t h e o r i g i n a l a ) i s " + a ) ;
System . o u t . p r i n t l n ( " A n g l e o f a i s " + a . a n g l e ( ) ) ;
9 a . times ( b ) ;
System . o u t . p r i n t l n ( " a = a ∗ b i s " + a ) ;
11
/ / T e s t i n g PolarComplex
13 P o l a r C o m p l e x c = new P o l a r C o m p l e x ( 1 0 . 0 , Math . P I / 6 . 0 ) ;
P o l a r C o m p l e x d = new P o l a r C o m p l e x ( 1 . 0 , Math . P I / 3 . 0 ) ;
15 System . o u t . p r i n t l n ( " c i s " + c) ;
System . o u t . p r i n t l n ( " d i s " + d ) ;
17 c . add ( d ) ;
System . o u t . p r i n t l n ( " c = c + d i s " + c ) ;
19 c . minus ( d ) ;
System . o u t . p r i n t l n ( " c − d ( which i s t h e o r i g i n a l c ) i s " + c ) ;
21 c . t i m e s ( d ) ;
System . o u t . p r i n t l n ( " c = c ∗ d i s " + c ) ;

66 105
Complex Number as ADT

User-defined data types can also be organized as ADTs.


Let’s create a "Complex" ADT for complex numbers.

p u b l i c i n t e r f a c e Complex {
2 p u b l i c double r e a l P a r t ( ) ;
p u b l i c double imagPart ( ) ;
4 p u b l i c d o u b l e modulus ( ) ;
p u b l i c d o u b l e argument ( ) ;
6 p u b l i c v o i d add ( Complex c ) ;
p u b l i c v o i d minus ( Complex c ) ;
8 p u b l i c v o i d t i m e s ( Complex c ) ;
}

67 105
Complex Number as ADT

c l a s s CartesianComplex {
2
...
4
p u b l i c v o i d add ( Complex c ) { . . . }
6 p u b l i c v o i d minus ( Complex c ) { . . . }
p u b l i c v o i d t i m e s ( Complex c ) { . . . }
8 }

10 c l a s s PolarComplex {

12 ...

14 p u b l i c v o i d add ( Complex c ) { . . . }
p u b l i c v o i d minus ( Complex c ) { . . . }
16 p u b l i c v o i d t i m e s ( Complex c ) { . . . }
}

68 105
Complex Number as ADT

1 Complex a = new C a r t e s i a n C o m p l e x ( 1 0 . 0 , 1 2 . 0 ) ;
Complex b = new C a r t e s i a n C o m p l e x ( 1 . 0 , 2 . 0 ) ;
3
Complex c = new P o l a r C o m p l e x ( 1 0 . 0 , Math . P I / 6 . 0 ) ;
5 Complex d = new P o l a r C o m p l e x ( 1 . 0 , Math . P I / 3 . 0 ) ;

7 System . o u t . p r i n t l n ( " T e s t i n g Combined : " ) ;


System . o u t . println ( "a is " + a) ;
9 System . o u t . println ( "d is " + d) ;
a . minus ( d ) ;
11 System . o u t . println ( "a = a − d is " + a) ;
a . times ( d ) ;
13 System . o u t . println ( "a = a∗d is " + a) ;
d . add ( a ) ;
15 System . o u t . println ( "d = d + a is " + d) ;
d . times ( a ) ;
17 System . o u t . println ( "d = d∗a is " + d) ;

69 105
Presentation Outline

1 Abstraction

2 Abstract Data Types


Complex Number
List

3 Modelling Tools and Languages

4 References

70 105
List

List is one of the most basic types of data collection.


▶ In general, we keep items of the same type (class) in one list.

Typical operations on a data collection:


▶ Add data
▶ Remove data
▶ Query data
▶ The details of the operations vary from application to application. The overall theme is the
management of data.

71 105
List

A List ADT is a dynamic linear data structure.


▶ A collection of data items, accessible one after another starting from the beginning (head) of
the list.
Examples of List ADT operations:
▶ Create an empty list
▶ Determine whether a list is empty
▶ Determine number of items in the list
▶ Insert an item at a given position
▶ Remove an item at a position
▶ Remove all items
▶ Read an item from the list at a position

72 105
List

1 p u b l i c i n t e r f a c e M yL i st {
p u b l i c boolean isEmpty ( ) ;
3 public int size () ;
public Object g e t F i r s t ( ) ;
5 public Object getAt ( i n t index )
p u b l i c boolean c o n t a i n s ( Object item ) ;
7 p u b l i c void i n s e r t F i r s t ( Object item ) ;
p u b l i c void i n s e r t ( i n t index , Object item )
9 public Object removeFirst ( ) ;
p u b l i c O b j e c t remove ( i n t i n d e x ) ;
11 public void print ( ) ;
}

The MyList above defines the operations (methods) we would like to have in a List ADT.
The operations shown here are just a small sample. An actual List ADT usually contains
more operations.
73 105
List

We will consider two implementation of List ADT, both using the interface MyList.

74 105
List Implementation via Array

A fixed-sized List.

Use array of a sequence of n elements.

75 105
List Implementation via Array

We now create a class MyArrayList as an implementation of the interface MyList (a


user-defined interface).

76 105
List Implementation via Array

For insertion into first position, need to shift "right" (starting from the last element) to
create room.

77 105
List Implementation via Array

For deletion of first element, need to shift “left” (starting from the first element) to close
gap.

78 105
List Implementation via Array

Question: Time Efficiency?


▶ Retrieval: getFirst()
Always fast with 1 read operation.
▶ Insertion: insertFirst(Object item)
Shifting of all n items – bad!
▶ Insertion: insert(int index, Object item)
Inserting into the specified position.
Best case: No shifting of items (add to the last place).
Worst case: Shifting of all items (add to the first place).
▶ Deletion: removeFirst(Object item)
Shifting of all n items – bad!
▶ Deletion: remove(int index)
Delete the item at the specified position.
Best case: No shifting of items (delete the last item).
Worst case: Shifting of all items (delete the first item).

79 105
List Implementation via Array

Question: What is the Space Efficiency?


▶ Size of array collection limited by MAX_SIZE. Problems
We don’t always know the maximum size ahead of time.
If MAX_SIZE is too liberal, unused space is wasted.
If MAX_SIZE is too conservative, easy to run out of space.
▶ Idea: make MAX_SIZE a variable, and create/copy to a larger array whenever the array runs
out of space.
No more limits on size.
But copying overhead is still a problem.
▶ Insertion: insert(int index, Object item)
Inserting into the specified position.
Best case: No shifting of items (add to the last place).
Worst case: Shifting of all items (add to the first place).
▶ When to use such a list?
For a fixed-size list, an array is good enough!
For a variable-size list, where dynamic operations such as insertion/deletion are common, an array
is a poor choice; better alternative – Linked List.

80 105
List Implementation via Linked List

81 105
List Implementation via Linked List

82 105
List Implementation via Linked List

83 105
List Implementation via Linked List

84 105
List Implementation via Linked List

Idea
▶ Each element in the list is stored in a node, which also contains a next pointer (reference).
▶ Allow elements in the list to occupy non-contiguous memory.
▶ Order the nodes by associating each with its neighbour(s).

85 105
List Implementation via Linked List

A sequence of 4 items < a0, a1, a2, a3 >.


We need a head to indicate where the first node is.
From the head we can get to the rest.

86 105
List Implementation via Linked List

The insertFirst() method.

87 105
List Implementation via Linked List

The removeFirst() method.

88 105
List Implementation via Linked List
The insert(int index, Object item) method.

The removeAt(int index) method.

89 105
Enhancements of Linked List

To address the issue that adding to the end is slow, add an extra data member called tail.

Allow cycling through the list repeatedly.

90 105
Enhancements of Linked List

Often, we need to move backward as well.


Use a "prev" pointer to allow backward traversal.

91 105
Presentation Outline

1 Abstraction

2 Abstract Data Types

3 Modelling Tools and Languages

4 References

92 105
Modelling Tools and Languages

UML stands for Unified Modeling Language.


▶ Language: express idea, not a methodology.
▶ Modeling: Describing a software system at a high level of abstraction.
▶ Unified: UML has become a world standard.

It is a industry-standard graphical language for specifying, visualizing, constructing, and


documenting the artifacts of software systems.
UML uses mostly graphical notations to express the OO analysis and design of software
projects.
Simplifies the complex process of software design.

93 105
UML Benefits

Use graphical notation: more clearly than natural language (imprecise) and code (too
detailed).
Help acquire an overall view of a system.
UML is not dependent on any one language or technology.
UML moves us from fragmentation to standardization.

94 105
UML diagrams

95 105
Class Diagram

A class diagram depicts classes and their interrelationships.


Used for describing the internal structure of a software system.
Provide a conceptual model of the system in terms of entities and their relationships.
Detailed class diagrams are used for developers.

96 105
Class

p u b l i c c l a s s Car {
2 protected String licensePlate ;
p r o t e c t e d b o o l e a n isOn ;
4
p u b l i c Car ( S t r i n g l i c e n s e P l a t e , b o o l e a n isOn ) {
6 this . license = licensePlate ;
t h i s . isOn = isOn ;
8 }

10 v o i d turnOn ( ) { ... }

12 void turnOff ( ) { ... }

14 @Override
public String toString () { ... }
16 }

97 105
Hierachy

1 p u b l i c c l a s s S e l f D r i v i n g C a r e x t e n d s Car {
boolean i s S e l f D r i v i n g ;
3
p u b l i c S e l f D r i v i n g C a r ( b o o l e a n isOn ,
5 String license ,
boolean i s S e l f D r i v i n g ) {
7 s u p e r ( isOn , l i c e n s e ) ;
this . isSelfDriving = isSelfDriving ;
9 }

11 @Override
v o i d turnOn ( ) { ... }
13
@Override
15 void turnOff ( ) { ... }

17 void turnSelfDrivingOn ( ) { . . . }
void turnSelfDrivingOff ( ) { . . . }
19
@Override
21 public String toString () { ... }
}

98 105
Abstract Class

1 p u b l i c abstract c l a s s Shape {
protected String color ;
3 protected boolean f i l l e d ;

5 p u b l i c Shape ( ) { ... }
...
7
public abstract double getArea();
9 public abstract double getPerimeter();
}
11
p u b l i c c l a s s C i r c l e e x t e n d s Shape {
13 p r i v a t e double radius ;

15 public Circle () { ... }


...
17
@Override
19 p u b l i c double getArea ( ) { ... }

21 @Override
p u b l i c double getPerimeter ( ) { ... }
23 }

99 105
Association

1 p u b l i c c l a s s Customer {
private String id ;
3 p r i v a t e S t r i n g name ;
p r i v a t e L i s t < Order > o r d e r s ;
5
p u b l i c Customer ( ... ) {
7 ...
}
9 }

11 p u b l i c c l a s s Order {
private String itemId ;
13 private String quantity ;

15 p u b l i c Order ( S t r i n g i t e m I d , S t r i n g q u a n t i t y ) {
t h i s . itemId = itemId ;
17 this . quantity = quantity ;
}
19 }

100 105
Association

1 p u b l i c c l a s s Customer {
private String id ;
3 p r i v a t e S t r i n g name ;

5 p u b l i c Customer ( ... ) {
...
7 }
}
9
p u b l i c c l a s s Order {
11 private String itemId ;
private String quantity ;
13 p r i v a t e Customer c u s t o m e r ;

15 p u b l i c Order ( ... ) {
...
17 }
}

101 105
Interface

1 public i n t e r f a c e Movable {
void moveUp ( ) ;
3 void moveDown ( ) ;
void moveLeft ( ) ;
5 void moveRight ( ) ;
}
7
p u b l i c c l a s s M o v a b l e P o i n t i m p l e m e n t s Movable {
9 private int x ;
private int y ;
11
p u b l i c MovablePoint ( ... ) { ... }
13
@Override
15 p u b l i c v o i d moveUp ( ) { ... }

17 ...
}

102 105
A Complete Example

103 105
Presentation Outline

1 Abstraction

2 Abstract Data Types

3 Modelling Tools and Languages

4 References

104 105
References

Allen B. Downey, Chris Mayfield, Think Java, (2016).


Graham Mitchell, Learn Java the Hard Way, 2nd Edition, (2016).
Cay S. Horstmann, Big Java - Early Objects, 7e-Wiley, (2019).
James Gosling, Bill Joy, Guy Steele, Gilad Bracha, Alex Buckley, The Java Language Specification -
Java SE 8 Edition, (2015).
Martin Fowler, UML Distilled - A Brief Guide To The Standard Object Modeling Language,
(2004).
Richard Warburton, Object-Oriented vs. Functional Programming - Bridging the Divide
Between Opposing Paradigms, (2016).
Naftalin, Maurice Wadler, Philip Java Generics and Collections, O’Reilly Media, (2009).
Eric Freeman, Elisabeth Robson Head First Design Patterns - Building Extensible and
Maintainable Object, Oriented Software-O’Reilly Media, (2020).
Alexander Shvets Dive Into Design Patterns, (2019).

105 / 105
Thank You!

You might also like