0% found this document useful (0 votes)
5 views60 pages

OOP Revision

The document provides an overview of Object-Oriented Programming (OOP) concepts, including coupling, cohesion, encapsulation, inheritance, and polymorphism. It emphasizes best practices such as loose coupling, high cohesion, and the use of access modifiers, as well as the differences between abstract classes and interfaces. Additionally, it covers JUnit testing and collections in Java, highlighting their utility and various implementations.

Uploaded by

h4nvktcphs
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)
5 views60 pages

OOP Revision

The document provides an overview of Object-Oriented Programming (OOP) concepts, including coupling, cohesion, encapsulation, inheritance, and polymorphism. It emphasizes best practices such as loose coupling, high cohesion, and the use of access modifiers, as well as the differences between abstract classes and interfaces. Additionally, it covers JUnit testing and collections in Java, highlighting their utility and various implementations.

Uploaded by

h4nvktcphs
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/ 60

Software Development 2

OOP Revision

F27SB
Example Implementation
public class Dog
{
//Individual characteristics (instance fields).
FIELDS
private String name;

//constructor
public Dog(String name) {
this.name = name; CONSTRUCTOR
}
//accessor method
private String getName() {
return name;
METHODS
}
}
OOP CONCEPTS
Coupling
• Coupling refers to links between separate units
of a program.
• If two classes depend closely on many details
of each other, we say they are tightly coupled.
• We aim for loose coupling.
• (A class diagram provides (limited) hints at the
degree of coupling.)
Loose coupling
• We aim for loose coupling.
• Loose coupling increases maintainability.
• No public fields/member variables
• Do not use public fields of other classes
either
• Use accessor and mutator methods
• Within limits!
Tight coupling
• We try to avoid tight coupling.
• A class uses a plethora of methods from
another class
• Relying heavily on constants and variables
defined in another class
• Class doesn’t work in isolation if taken out of
the current project.
Encapsulation
• = hiding information from view.
• Only information about WHAT a unit, e.g.
class, can do should be visible from the
outside.
• The HOW should be hidden/ “encapsulated”.
• Reduces coupling.
Cohesion
• Cohesion refers to the number and diversity of
tasks that a single unit is responsible for.
• If each unit is responsible for one single logical
task, we say it has high cohesion.
• ‘Unit’ applies to classes, methods and modules
(packages).
• We aim for high cohesion.
High cohesion
• We aim for high cohesion.
• High cohesion makes it easier to:
– understand what a class or method does;
– use descriptive names for variables,
methods and classes;
– reuse classes and methods.
– Read other people’s code.
High cohesion
• Class level:
– Classes should represent one single, well
defined entity;
– hold all the information they need
• Method level:
– A method should be responsible for one and
only one well defined task.
Responsibility-driven design (RDD)
• Question: where should we add a new method
(which class)?
• Each class should be responsible for
manipulating its own data.
• The class that owns the data should be
responsible for processing it.
• RDD leads to low coupling.
JUNIT TESTS
Example Test
@Test
public void testMultiply() {

//MyClass is tested
MyClass tester = new MyClass();

//Check if multiply(10,5) returns 50


assertEquals("Result", 50,
tester.multiply(10, 5));
}
Assertions
Statement Description
fail(String) Let the method fail. Might be used to
check that a certain part of the code is
not reached.
assertTrue(true) / Checks whether condition is true/false.
assertTrue(false)

assertsEquals(expected, Tests that two values are the same.


actual)

assertNull(object), Checks that the object is (not) null.


assertNotNull(object)

assertSame(expected, Checks that both variables refer to the


actual), same/ a different object.
assertNotSame(e,a)
INHERITANCE
Inheritance

Superclass

Superclass of Poodle

Subclass of Animal

Subclass of Dog
Subclass of Animal
Inheritance
Inheritance
Substitution

Supertype

Supertype of Poodle

Subtype of Animal

Subtype of Dog
Subtype of Animal
Object types

Checked at run
time
Static type

Dynamic type
Checked at
compile time
Substitution

Dynamic type can be a subtype


where the static type of
supertype is required.
Polymorphic variables

• Object variables in Java are polymorphic.

➡They can hold objects of more than one type.

• They can hold objects with the dynamic type


of the declared static type, or of subtypes of
the declared static type.
Type Casting
Upcasting

Downcasting
Type Casting
Type Casting
Dynamic method lookup

• Java uses the dynamic type for method


lookup at run time
• If the method is not found, it goes up the
inheritance tree to the superclass
• repeat until found
Method lookup
Overriding and overloading
• Overriding refers to redefining a
method/constructor of a superclass in a subclass
• same return type, visibility modifier, and
parameter list
• Overloading refers to defining a
method/constructor with the same name of a
method/constructor in this class or any superclass
• different return type, or parameter list
Overriding
Overriding
Overloading
Overloading
Overloading
VISIBILITY AND ACCESS MODIFIERS
Access/Visibility Modifiers

Modifier Class Package Subclass World


public Y Y Y Y
protected Y Y Y N
(none) Y Y N N
private Y N N N
Good practice for Access Levels

• Use the most restrictive access level that


makes sense for a particular member.
• Use private unless you have a good reason not
to.
• Avoid public fields except for constants.
• Public fields tend to limit your flexibility in
changing your code.
static final Constants
• static = variables that are common to all
objects; does not require creating a new
instance. -> “Class field”
• final = the value of this field cannot be
changed. -> “Constant”

37
ABSTRACT CLASSES AND INTERFACES
Abstract methods
• Abstract methods have abstract in the
signature.
• Abstract methods have no body (without braces,
and followed by a semicolon).

• Abstract methods make the class abstract.

39
Abstract classes
• Abstract classes cannot be instantiated, i.e. no instances
of this type can be created.
• Its purpose is to serve as a superclass for other classes.
• Concrete subclasses complete the implementation.
• A subclass must implement all abstract methods
(otherwise it will be abstract itself)
• Abstract classes may contain abstract methods and
implemented methods (i.e. with a body) at the same
time.

40
Abstract classes
Why Abstract Classes

• Implement diverging behaviour in subclasses.


• Abstract classes cannot be instantiated
• Guarantee that no instance of this object
will “live in your Java world”.
Interfaces

• All methods are abstract.


• There are no constructors.
• All methods are public.
• All fields are public, static, and final.
• Constants
Interfaces as types

• Implementing classes do not inherit code, but


...
• ... implementing classes are subtypes of the
interface type.
• So, polymorphism (method overriding) is
available with interfaces as well as classes.
Interfaces
Interfaces
Interfaces
Multiple Inheritance
• Classes can extend 0 - 1 classes
• Doesn’t matter if they are abstract or not
• Classes can implement 0 - n interfaces
Summary: Java Interfaces
• A Java Interface is an abstract type that is used to
specify an interface (= set of features) that
classes must implement.
• Similar function to Abstract Classes, but without
any implementation (fully abstract).
• Provides shared type information, no code
inheritance.
• Tool for (multiple) Inheritance, Abstraction,
Information Hiding -> reduce coupling
Interfaces vs. Abstract Classes
Feature Interface Abstract Class
Multiple Inheritance A class may implement A class may extend only one
several interfaces. abstract class.

Default An interface can’t provide An abstract class can provide


implementation any code at all. implemented methods.

Constants Static final constants (= Both instance and static


class fields) only. constants are possible.

Third party An interface A third party class must be


convenience implementation may be rewritten to extend only from
added to any existing third the abstract class.
part class.
When to choose which one?
• How similar is their behaviour? Any shared implemented methods?
• code inheritance from abstract classes
• How modular does the code need to be? How much information
hiding is required?
• Interfaces allow better information hiding
• Need multiple inheritance?
• interfaces allow a more flexible and extendible code structure.
COLLECTIONS
Collections
• Utility interfaces and classes
Diamond
• java.utils.*; notation
• Polymorphic
• Can use interface as the static type
List<String> l = new LinkedList<>();
• Hold objects that are an instanceof the type given in <>
• Includes subclasses, i.e. substitution
Collections

• Only hold objects


• No “primitive” types allowed

Map<int,int> map = new HashMap<>();


Map<Integer,Integer> map = new HashMap<>();
Examples

instanceof
Examples
Examples
List, Map and Set
• Alternative ways to group objects.
• Varying implementations available:
– ArrayList, LinkedList
– HashSet, TreeSet
• Sets do not hold duplicates.
• Maps have unique keys.
• But HashMap is unrelated to HashSet, despite similar
names.
• The second word reveals organisational relatedness.
THAT’S IT!

You might also like