Object-Oriented Programming

Содержание

Слайд 2

Course Contents

Part I: Object-Oriented Concepts and Principles
Part II: Object-oriented Programming
Closer look at

Course Contents Part I: Object-Oriented Concepts and Principles Part II: Object-oriented Programming
the concepts of OOP

OOP, Rovaniemi University of Applied Sciences

Слайд 3

Member Variables

Variables defined inside a class are called member variables
Member variables fall

Member Variables Variables defined inside a class are called member variables Member
into two categories: instance variables and class variables (static variables)

OOP, Rovaniemi University of Applied Sciences

Слайд 4

Instance Variables

All objects have their own copies of instance variables
System allocates memory

Instance Variables All objects have their own copies of instance variables System
for instance variables at object creation time
Instance variables can be accessed only through an instance, for example Vector v = new Vector(); int c=v.elementCount;
The state of an object is specified by the values of its instance variables

OOP, Rovaniemi University of Applied Sciences

Слайд 5

Class (Static) Variables

The runtime system allocates a class variable once per class,

Class (Static) Variables The runtime system allocates a class variable once per
regardless of the number of instances created of that class
All instances of the same class share the same copy of class variables
The system allocates memory for a class variable the first time it encounters the class (=loads it into memory)
You can access class variables either through an instance or through the class itself
The latter is better style, for example String s = Integer.toString(10);

OOP, Rovaniemi University of Applied Sciences

Слайд 6

Example of Instance and Class Variables in Java

public abstract class Shape
{
public

Example of Instance and Class Variables in Java public abstract class Shape
static int a_numberOfShapes=0;
private Color a_color;
public Shape(){
Shape.a_numberOfShapes++;
a_color = Color.BLACK;
}
public Shape(Color c){
Shape.a_numberOfShapes++;
a_color = c;
}
}

OOP, Rovaniemi University of Applied Sciences

Слайд 7

Methods

The code that describes how to perform an operation on a specific

Methods The code that describes how to perform an operation on a
object type is called a method
In different OOP languages, methods can also be called as functions or operations, all meaning the same thing.
Variables and methods can be called with a common name class members
Methods fall into two categories: instance methods and class methods

OOP, Rovaniemi University of Applied Sciences

Слайд 8

Instance Methods

Both instance and class members can be referenced from an instance

Instance Methods Both instance and class members can be referenced from an
method
If no instance name is given when referring to an instance variable or method, the system uses the current instance (object self-reference)

OOP, Rovaniemi University of Applied Sciences

Слайд 9

Class (Static) Methods

A class method is a static method in some class.

Class (Static) Methods A class method is a static method in some

It may not access the instance variables or methods of the class, but only the other static members of the class
A static method can access an instance variable or method only if the instance (object) name is mentioned before the variable/method name

OOP, Rovaniemi University of Applied Sciences

Слайд 10

Method Overloading

Method overloading means having two methods with the same name in

Method Overloading Method overloading means having two methods with the same name
the same class that differ in the amount and/or types of their arguments.
It is not legal to have two methods of the same name that differ only in their return types
Method overloading is not an O-O feature; it can exist in non-object languages as well.
Do not mix with method overriding!

OOP, Rovaniemi University of Applied Sciences

Слайд 11

Example of Method Overloading

public class Rectangle extends Shape
{
private int width;
private

Example of Method Overloading public class Rectangle extends Shape { private int
int height;
public Rectangle() {
width=0;
height=0;
}
public Rectangle(int w, int h) {
width=w;
height=h;
}
public Rectangle(int w, int h, Color c) {
super(c);
width=w;
height=h;
}
}

OOP, Rovaniemi University of Applied Sciences

Слайд 12

Coercion

Coercion and overloading often go hand in hand
Coercion occurs when an argument

Coercion Coercion and overloading often go hand in hand Coercion occurs when
of one type is converted into the expected type automatically
Example:
public float add( float a, float b );
int x=1, y=2;
float z = add(x,y);
When you call add() with int arguments, the arguments are converted into floats by the compiler (type cast)
To avoid coersion another overloaded method with int type of arguments could be added to the class:
public int add( int a, int b );

OOP, Rovaniemi University of Applied Sciences

Слайд 13

Exercise

Look through the Java API. Find an example of overloading and explain

Exercise Look through the Java API. Find an example of overloading and
it.

OOP, Rovaniemi University of Applied Sciences

Слайд 14

Variable Shadowing

public class Circle extends Shape
{
private int radius;
// Parameter radius shadows

Variable Shadowing public class Circle extends Shape { private int radius; //
member variable radius
public Circle(int radius) {
this.radius=radius;
}
public Circle(int r, Color circleColor) {
super(circleColor);
radius=r;
}
}
Shadowing means using the same names for member variables and method parameters/local variables
Sometimes used, but better to be avoided

OOP, Rovaniemi University of Applied Sciences

Слайд 15

Naming the Member Variables

A common way to avoid variable shadowing is to

Naming the Member Variables A common way to avoid variable shadowing is
follow a naming convention for member variables
For instance add a prefix to each member variable:
m_ as member, or
a_ as attribute
The latter one might be better, because letter m can also be incorrectly associated with the word method
Example: private int a_size;
For local variables and parameters it is then possible to use the same name without the prefix
How could you fix the example on the previous slide to avoid variable shadowing?

OOP, Rovaniemi University of Applied Sciences

Слайд 16

Variable Shadowing Example Fixed

Rename member variable radius to a_radius
Parameter radius no longer

Variable Shadowing Example Fixed Rename member variable radius to a_radius Parameter radius
shadows the member variable
public class Circle extends Shape
{
private int a_radius;
public Circle(int radius) {
a_radius=radius;
}
}

OOP, Rovaniemi University of Applied Sciences

Слайд 17

Object Self-reference

In OOP languages, a special keyword is used to refer to

Object Self-reference In OOP languages, a special keyword is used to refer
the current instance of an object
this in Java, C++ and C#
Self-reference contains the object type and the value of the current object instance
Self-reference is used to access the object whenever a reference to it is needed inside the object
to access a member variable when shadowed by local variables
to pass the object itself as a function argument
to add the object itself to a collection
to call another constructor method in the same class

OOP, Rovaniemi University of Applied Sciences

Слайд 18

Constructor

A specialized method used to instantiate an object
The constructor function has the

Constructor A specialized method used to instantiate an object The constructor function
same name as the class. It is never called directly, but the run-time system calls it when a new object is created
Constructors are usually overloaded; a class contains multiple constructors, which have a different set of parameters

OOP, Rovaniemi University of Applied Sciences

Слайд 19

Destructor

Destructor is a specialized method, which is called when an object is

Destructor Destructor is a specialized method, which is called when an object
deleted
Its purpose is to release the resources the object may have allocated
Destructor cannot be overloaded and it cannot have any arguments
Constructor and destructor methods can’t be inherited
When a class is instantiated, the system first calls the constructor of its superclass and the superclass’s superclass until it reaches the root of the inheritance hierarchy

OOP, Rovaniemi University of Applied Sciences

Слайд 20

Constructor Example 1

public class Rectangle extends Shape
{
private int width;
private int

Constructor Example 1 public class Rectangle extends Shape { private int width;
height;
public Rectangle() {
width=0;
height=0;
}
public Rectangle(int w, int h)
{
width=w;
height=h;
}
public Rectangle(int w, int h, Color c)
{
super(c);
width=w;
height=h;
}
}

OOP, Rovaniemi University of Applied Sciences

Слайд 21

Constructor Example 2

public class TestShape
{
public void someMethod()
{
Color myColor

Constructor Example 2 public class TestShape { public void someMethod() { Color
= new Color(100, 170, 15);
// Call parameterless consructor
Rectangle r1 = new Rectangle ();
// Call constructor with two int type of parameters
Rectangle r2 = new Rectangle(5,8);
// Call constructor with two int and one Color type of parameters
Rectangle r3 = new Rectangle(7, 15, myColor);
}
}

OOP, Rovaniemi University of Applied Sciences

Слайд 22

Method overriding

Method overriding means providing a replacement method in a new class

Method overriding Method overriding means providing a replacement method in a new
for a method inherited from the base class; i.e. we give a new implementation for an inherited superclass method in the subclass
The replacement method must have exactly the same name, argument list and return type as the inherited method
Overriding occurs when attributes and methods are inherited in the normal manner, but are then modified to the specific needs of the new class

OOP, Rovaniemi University of Applied Sciences

Слайд 23

Example of Method Overriding 1

public abstract class Shape
{
public static int a_numberOfShapes=0;

Example of Method Overriding 1 public abstract class Shape { public static
protected Color a_color;
public Shape(Color c) {
Shape.a_numberOfShapes++;
a_color = c;
}
public long getArea() { return 0; };
public abstract long getCircumference();
}

OOP, Rovaniemi University of Applied Sciences

Слайд 24

Example of Method Overriding 2

public class Circle extends Shape
{
private int a_radius;
public

Example of Method Overriding 2 public class Circle extends Shape { private
Circle(int radius, Color circleColor) {
super(circleColor);
a_radius=radius;
}
public long getCircumference() {
return Math.round(2* Math.PI*m_radius);
}
public long getArea() {
return Math.round(Math.PI*m_radius*m_radius);
}
}

OOP, Rovaniemi University of Applied Sciences

Слайд 25

Redefinition

Occurs when a subclass defines a method using the same name as

Redefinition Occurs when a subclass defines a method using the same name
a method in the superclass but with a different type signature
The change in type signature (parameter list) is what differentiates redefinition from overriding
Two different techniques to resolve the redefined name: merge model (Java, C#) and hierarchical model (C++)
Merge model: all the currently active scopes are examined to find the best match
Hierarchical model: scopes are examined one by one, starting from the subclass scope. If the name is defined there, the closest match in that scope will be the one selected
Redefinition is bad programming style: easy to cause confusion and errors

OOP, Rovaniemi University of Applied Sciences

Слайд 26

Example of Redefinition

class Parent {
public void example(int a) {…}
}
class Child extends

Example of Redefinition class Parent { public void example(int a) {…} }
Parent {
public void example(int a, int b) {}
Let’s create an instance of the child and execute the method with one argument:
Child c = new Child();
c.example(7);
In Java and C#, the method from the parent class will be selected
In C++ the code will produce a compilation error. Why?

OOP, Rovaniemi University of Applied Sciences

Слайд 27

Variable Hiding

Within a class, a member variable that has the same name

Variable Hiding Within a class, a member variable that has the same
as a member variable in the superclass hides the superclass's member variable
Within the subclass, the member variable in the superclass can no longer be referenced by its simple name
Instead, the superclass member variable must be accessed through the super operator (Java, C++)
Variable hiding is bad programming style
Easy to cause confusion and errors
Just because a programming language allows you to do something, it does not always mean that it is a desirable thing to do!

OOP, Rovaniemi University of Applied Sciences

Слайд 28

Example of Variable Hiding

class Employee {
protected int salary;
protected int hours;
}
class

Example of Variable Hiding class Employee { protected int salary; protected int
PartTimeEmployee extends Employee {
protected int salary;
public void setSalary(int sal) {
super.salary = sal; // Sets the superclass salary
}
public int calculateMonthlySalary() {
// Uses superclass hours, but subclass salary
return hours * salary;
}
}

OOP, Rovaniemi University of Applied Sciences

Слайд 29

Exercise

Consider the Java API class java.io.Writer
What kind of examples of method

Exercise Consider the Java API class java.io.Writer What kind of examples of
overriding can you find in the subclasses of class Writer?
Find another example of method overriding in the Java API

OOP, Rovaniemi University of Applied Sciences

Слайд 30

Access Specifiers (Visibility Identifiers)

There are three parts in a class, which have

Access Specifiers (Visibility Identifiers) There are three parts in a class, which
different protection level:
public part
protected part
private part
An access specier is given to a class and to all members of the class
Public variables and methods are visible to all classes
Protected members are only visible inside the class itself and its subclasses

OOP, Rovaniemi University of Applied Sciences

Слайд 31

Access Specifiers

Private members are only visible inside the class itself
Public and protected

Access Specifiers Private members are only visible inside the class itself Public
parts define the class’s interface to other classes
Constructor methods must be declared as public
Otherwise the class cannot be instantiated as constructors are always called outside the class itself
With the rare exception of singleton pattern

OOP, Rovaniemi University of Applied Sciences

Слайд 32

Access Specifiers

OOP, Rovaniemi University of Applied Sciences

Access Specifiers OOP, Rovaniemi University of Applied Sciences

Слайд 33

Private Data – Public Accessor methods

Member variables are usually declared as private
Public

Private Data – Public Accessor methods Member variables are usually declared as
get and set methods are used to set and get the variable values
Advantages of using set and get methods:
We can give a read-only access to certain data by specifying only the get method
We can check for the validity of the data in the set method, e.g. not allow negative values for person’s age or height
We can ensure that required updates are done, e.g. a field value is updated on the screen as well
We can change the data structures inside the class, yet keep its public interface untouched causing no side-effects outside the class

OOP, Rovaniemi University of Applied Sciences

Слайд 34

Checking Parameters for Validity

Methods should be made as general as practical
Do

Checking Parameters for Validity Methods should be made as general as practical
not set arbitrary restrictions on method parameters
Yet most methods have restrictions on what values may be passed into their parameters
E.g. no negative values, no null values
Document clearly all such restrictions
Check the validity of parameters before the execution of the method
If the check fails, exit quickly and cleanly with an appropriate exception
Public methods should throw an appropriate exception (Java: Null Pointer-, IllegalArgument-, IndexOutOfBounds-, etc.) For non-public methods use assertions, since you are the author of the package and therefore responsible for any illegal method calls

OOP, Rovaniemi University of Applied Sciences

Слайд 35

Example of Using Access Speciers with Set and Get Methods

public class Circle

Example of Using Access Speciers with Set and Get Methods public class
extends Shape
{
private int radius;
public Circle() {
radius=0;
}
public int getRadius() {
return radius;
}
public void setRadius(int r) {
if (r >= 0) // Checking validity
radius = r;
else
radius = 0;
}
}

OOP, Rovaniemi University of Applied Sciences

Слайд 36

Exercise: Access Specifiers - Set and Get Methods

Modify the class Shape so

Exercise: Access Specifiers - Set and Get Methods Modify the class Shape
that the colour will be represented with three int type of variables red, green and blue instead of a single Color type of a variable. Red, green and blue are integer values from 0 to 255.
Make the required mapping between the new and old data structure in the setColor, getColor and constructor –methods of class Shape.
Only change the method implementations, not the prototypes/signatures
You can create a new Color type of an object by giving the integer values as parameters to Color class constructor For instance Color newColor = new Color(r, g, b);
You can get the RGB –values from a Color type of an object using the methods getRed(), getGreen() and getBlue(). For instance int green = newColor.getGreen();
You may also add new set and get methods for setting and getting the attributes red, green and blue.
What changes are needed outside of the class Shape?

OOP, Rovaniemi University of Applied Sciences

Слайд 37

Exercise: Checking Parameter Values for Validity

Add set and get methods for the

Exercise: Checking Parameter Values for Validity Add set and get methods for
new int type of member variables red, green and blue in the modified Shape class
Check in the set methods that the parameter value is in the range from 0 to 255. If it is not, leave the attribute value unchanged (and throw an exception or return an error code)

OOP, Rovaniemi University of Applied Sciences

Слайд 38

Using Protected Instance Variables

Advantages
Subclasses can modify values directly
Slight increase in performance
Avoid set/get

Using Protected Instance Variables Advantages Subclasses can modify values directly Slight increase
function call overhead
Disadvantages
No validity checking
subclass can assign illegal value
Implementation dependent
subclass methods more likely dependent on superclass implementation
superclass implementation changes may result in subclass modifications
Fragile (brittle) software

OOP, Rovaniemi University of Applied Sciences

Слайд 39

Abstract Class

Abstract methods are methods that are declared but not yet implemented
Abstract

Abstract Class Abstract methods are methods that are declared but not yet
methods have name, return value and arguments, but no method body (implementation)
Also called as deferred methods, or in C++ pure virtual methods
Only abstract classes may have abstract methods; if a class has even one abstract method the class itself must be declared as abstract
An abstract class cannot be instantiated, but it can be inherited

OOP, Rovaniemi University of Applied Sciences

Слайд 40

Purpose of Abstract Classes

Allow a programmer to define common interface for a

Purpose of Abstract Classes Allow a programmer to define common interface for
group of classes
Allow a programmer to use polymorphic method calls (late binding)
For example in a collection of classes representing geometric shapes, we can define a method to calculate the area of the shape in each of the subclasses Circle, Rectangle, Triangle
Suppose a programmer defines a polymorphic variable of class Shape that will, at various times, contain instances of each different shape. Compiler will permit message getArea() to be used with this variable only if it can ensure that the message will be understood by any value that can be associated with the variable
Solution is to declare an abstract method getArea() in the superclass Shape

OOP, Rovaniemi University of Applied Sciences

Слайд 41

Abstract Class vs. Interface

Besides abstract methods, an abstract class can contain variable

Abstract Class vs. Interface Besides abstract methods, an abstract class can contain
definitions and method implementations
Can inherit other abstract classes and implement interfaces
An interface can only contain abstract methods and constant definitions
”Pure abstract class”
Can inherit other interfaces and only them
Purpose of Interfaces
Interfaces define and standardize the ways in which people and systems can interact with one another

OOP, Rovaniemi University of Applied Sciences

Слайд 42

Polymorphism

Generally, the ability to appear in many forms
In OOP polymorphism refers to

Polymorphism Generally, the ability to appear in many forms In OOP polymorphism
a programming language's ability to process objects differently depending on their class
Polymorphism is a characteristic that greatly reduces the effort required to extend an existing OO system

OOP, Rovaniemi University of Applied Sciences

Слайд 43

Polymorphism in OOP

We can refer to a subclass type of an object

Polymorphism in OOP We can refer to a subclass type of an
with a superclass type of a variable
The class of the referred object is not known at compile time
Responds at run time according to the actual class of the referred object (late binding)
Subclasses can override inherited superclass methods; we can have several implementations of the same method in the class hierarchy
For example, given a base class Shape, polymorphism enables the programmer to define different getArea() method for any number of derived classes, such as Circle, Rectangle and Triangle
No matter what shape an object is, applying the getArea() method to it will return the correct results (late binding)

OOP, Rovaniemi University of Applied Sciences

Слайд 44

Polymorphism Example 1

OOP, Rovaniemi University of Applied Sciences

Base class

Derived classes

Polymorphism Example 1 OOP, Rovaniemi University of Applied Sciences Base class Derived classes

Слайд 45

Polymorphism Example 2

A simple example of polymorphism is the method append in

Polymorphism Example 2 A simple example of polymorphism is the method append
the Java class StringBuffer
The argument to this method is declared as Object and thus can be any object type
The method has the following definition:
class StringBuffer {
String append(object value) {
return append( value.toString() );
}
}
The method toString is defferred. It is defined in class Object and redefined in a large number of different subclasses
Each of these definitions of toString will have slightly different effect: a Double will produce a textual representation of a numeric value; Color will generate a string that describes the red, green and blue values in the color, etc.

OOP, Rovaniemi University of Applied Sciences

Слайд 46

Exercises

In your own words, explain polymorphism
Consider again the Java API class java.io.Writer.

Exercises In your own words, explain polymorphism Consider again the Java API

(What kind of examples of method overriding can you find in the subclasses of class Writer?)
When programming, you should write your objects and methods to act on instances of Writer (instead of subclass types). Why?

OOP, Rovaniemi University of Applied Sciences

Слайд 47

Late Binding 1

Dynamic binding of messages (method calls) to method definitions
Polymorphism ensures

Late Binding 1 Dynamic binding of messages (method calls) to method definitions
that the proper version of the method is called based on the type of the object
Late binding only applies to instance methods; this sort of dynamic lookup does not happen for static/class methods. Why?

OOP, Rovaniemi University of Applied Sciences

Слайд 48

Late Binding 2

Actual operations can be bound to messages as soon as

Late Binding 2 Actual operations can be bound to messages as soon
the type of the object receiving the message is known
If this is known during the compilation, an early binding occurs, otherwise the mapping is done on run-time, late binding occurs
Early binding is typically more efficient in terms of hardware resource usage
Late binding is a mechanism to implement polymorphism, which is one of the main principles of OOP
Reminder: polymorphism - different type of objects invoke different methods in response to the same message (method call)

OOP, Rovaniemi University of Applied Sciences

Слайд 49

Virtual Operation

An operation which late binding can be applied to is called

Virtual Operation An operation which late binding can be applied to is
a virtual operation
In Java, all methods are virtual by default Method overriding can be prohibited by defining the method as final
In C++ all methods are non-virtual by default. Methods must by specified as virtual by using the virtual keyword

OOP, Rovaniemi University of Applied Sciences

Слайд 50

Group Work

Write down the names of the Shape, Triangle, Rectangle and Circle

Group Work Write down the names of the Shape, Triangle, Rectangle and
classes (see previos slide)
What kind of attributes the classes should have (to be able to calculate the area of the shape they represent)?
Find common attributes, if any, and move them to the common base class Shape
Add an abstract method getArea() to the base class
Implement the getArea() method in each of the subclasses. It should return the area of that particular shape
Area of a triangle = ½absinC, Area of a circle = ¶r2
Similarly add method getCircumference() to the superclass and subclasses

OOP, Rovaniemi University of Applied Sciences

Слайд 51

Group Work

Add a new subclass for the class Shape, for instance Parallelogram

Group Work Add a new subclass for the class Shape, for instance
( area = side1 * side2 * sin(angle) )
Use the functions Math.sin(angle in radians) and Math.toRadians(angle in degrees)
Create an instance of the new class in the Test class and call the printAreaAndCircumference for it

OOP, Rovaniemi University of Applied Sciences

Слайд 52

Other Forms of Polymorphism

The type of polymorphism described earlier is called pure

Other Forms of Polymorphism The type of polymorphism described earlier is called
polymorphism or inclusion polymorphism
Pure polymorphism occurs when a polymorphic variable is used as an argument in a method
Another type of polymorphism is parametric polymorphism, which is implemented in Java as generic classes and in C++ with template classes
Method overriding and overloading can also be considered as types of polymorphism

OOP, Rovaniemi University of Applied Sciences

Слайд 53

Multiple Inheritance

Sometimes it is tempting to inherit some attributes and methods from

Multiple Inheritance Sometimes it is tempting to inherit some attributes and methods
one class and others from another class. This is called multiple inheritance
Multiple inheritance means having more than one direct superclass
Multiple inheritance complicates the class hierarchy and creates potential problems in configuration control (sequences of multiple inheritance are more difficult to trace)

OOP, Rovaniemi University of Applied Sciences

Слайд 54

Problems with Multiple Inheritance

Name ambiguity
Inherited, different features can have the same name
Same

Problems with Multiple Inheritance Name ambiguity Inherited, different features can have the
feature may be inherited several times
Impact on substitutability
Overriding a method that has been inherited from several superclasses
deck.draw(), rectangle.draw()
Many types of tricks invented to overcome the problems
Make the program complicated, is it worth it?

OOP, Rovaniemi University of Applied Sciences

Слайд 55

Reference and Value Semantics

Reference semantics: variable values are references to objects (Java)
Assignment

Reference and Value Semantics Reference semantics: variable values are references to objects
x=y causes a pointer copy: both x and y refer to the same object after the assignment has been done.
Value semantics: variable values are the objects (default in C++)
Assignment x=y causes all the field values of object y to be copied to the fields of object x. Two separate, identical objects exist after the assigment has been performed

OOP, Rovaniemi University of Applied Sciences

Слайд 56

Reference and Value Semantics

Pure object languages use reference semantics
Value semantic type of

Reference and Value Semantics Pure object languages use reference semantics Value semantic
copying can be done with a separate cloning method.
Hybrid languages (such as C++) contain a special type for handling object references: a pointer type
Assignment xPointer = yPointer causes a pointer copy: both xPointer and yPointer refer to the same object after the assigment has been done.

OOP, Rovaniemi University of Applied Sciences

Имя файла: Object-Oriented-Programming-.pptx
Количество просмотров: 210
Количество скачиваний: 0