Principles of Programming and Software Engineering

Chapter 2

Object Oriented Programming &

Software Engineering

© 2006 Pearson Addison-Wesley. All rights reserved 2-1

Problem Solving and Software

Engineering

• Coding without a solution design increases debugging time

• A team of programmers is needed for a large software development project

• Teamwork requires:

– An overall plan

– Organization

– Communication

• Software engineering

– Provides techniques to facilitate the development of computer programs

© 2006 Pearson Addison-Wesley. All rights reserved 2-2

What is Problem Solving?

• Problem solving

– The process of taking the statement of a problem and developing a computer program that solves that problem

• A solution consists of:

– Algorithms

• Algorithm: a step-by-step specification of a method to solve a problem within a finite amount of time

– Ways to store data

© 2006 Pearson Addison-Wesley. All rights reserved 2-3

Achieving an Object-Oriented

Design: Abstraction and

Information Hiding

A modular solution to a problem should specify what to do, not how to do it

• Procedural abstraction

– When design a method as part of a solution, we specify each method before actually implement it. (separates the purpose of a method from its implementation.)

– It is essential to team projects. You will need to use methods written by others without knowing their algorithms.

– For example, Java API: Math.sqrt

© 2006 Pearson Addison-Wesley. All rights reserved 2-4

Abstraction and Information

Hiding

• Consider a collection of data and a set of operations on the data.

• Data abstraction

– Focus on what the data is as well as what the operations of data, not on the storage or implementation of the operations.

– Other modules of the solution will know what operation they can perform, but they will not know how the data is stored or how the operations are performed .

– Abstract data type (ADT)

• A collection of data and a set of operations on the data

– the operations’ specifications are known

– Data structure

• A construct that can be defined within a programming language implement

ADT

© 2006 Pearson Addison-Wesley. All rights reserved 2-5

Abstraction and Information

Hiding

• Abstraction tells you to write specification for each module for outside.

• Public view of a module

– Described by its specifications

• Private view of a module

– Details which should not be described by the specifications.

• Principle of information hiding

– Hide details within a module as private

– Ensure that no other module can tamper with these hidden details for protection purpose

– As a user of a module, you do not worry about the implementation details

– As an implementer of a module, you do not worry about the misuse of your module.

© 2006 Pearson Addison-Wesley. All rights reserved 2-6

How to Practice Abstraction and

Information Hiding

• Design phase: divide into function modules and give requirements

– The necessary controls for the class are left visible; The class interface is made visible; components (data fields and working mechanism) under the hood (private)

– The user is given only enough information to use the car/class

– The programmer can change the implementation details without affecting user’s code

© 2006 Pearson Addison-Wesley. All rights reserved 2-7

Java Interface

• /**

• * This interface describes the operations of a bag.

• *

• * @author Charles Hoot, Frank M. Carrano

• * @version 2.0

• */

• public interface BagInterface<T>

• {

/** Task: Adds a new entry to the bag Increases the number of entries by one.

* @param newEntry the object to be added as a new entry

* @return true if the addition is successful, or false if not */ public boolean add(T newEntry);

• }

/** Task: Removes the first occurrence of an entry. Decreases the number of entries by one.

* @param anEntry the object to be removed

* @return either the entry removed if the removal

* was successful, or null */ public T remove(T anEntry);

© 2006 Pearson Addison-Wesley. All rights reserved 2-8

Implement Interface

A class that implements an interface must state so at start of definition public class myClass implements someInterface

The class must implement every method declared in the interface

Multiple classes can implement the same interface

A class can implement more than one interface

An interface can be used as a data type, only those objects whose classes implement the interface can be passed in. public void someMethod (someInterface x)

© 2006 Pearson Addison-Wesley. All rights reserved 2-9

• public class LinkedBag<T> implements BagInterface<T>

• { private Node firstNode; // head reference to first node private Node lastNode; // tail reference to last node private int size; // number of entries in bag public LinkedBag()

{ clear();

} // end default constructor

• …

• } public boolean add(T newEntry)

{

Node newNode = new Node(newEntry); if (isEmpty()) else firstNode = newNode; lastNode.next = newNode; lastNode = newNode; size++; return true;

} // end add

© 2006 Pearson Addison-Wesley. All rights reserved 2-10

Implementing an Interface

Fig. 3-3 The files for an interface, a class that implements the interface, and the client.

Interface for Abstraction

Fig. 3-2 An interface provides well-regulated communication between a hidden implementation and a client.

© 2006 Pearson Addison-Wesley. All rights reserved 2-12

Object-Oriented Design

• Object-oriented approach to modularity

– Produces a collection of objects that have behaviors representing real-life entities that interact with each other produce a solution

• Object

– An instance of a class

– Combines data and operations on that data

• Encapsulation (encase, or enclose)

– Methods encapsulate actions

– Objects encapsulate data as well as actions

• E.g. the alarm clock encapsulates both time and operations such as “set the alarm”. You are also an object, and you interact with alarm clock by request the clock to set the alarm in the morning to wake you up.

– Clock performs operations such as set the time, advance the time, display the time.

© 2006 Pearson Addison-Wesley. All rights reserved 2-13

Object-Oriented Design

• Principles of object-oriented programming (OOP)

– Encapsulation

• Objects combine data and operations

– Inheritance

• Classes can inherit properties from other classes

– Polymorphism

• Objects can determine appropriate operations at execution time

© 2006 Pearson Addison-Wesley. All rights reserved 2-14

Inheritance

• A general or base class is first defined

• Then a more specialized class is derived by inheriting from this base class:

– Adding to details of the base class

– Revising details of the more general class

• Advantages

– Saves work

– Common properties and behaviors are define only once for all classes involved

© 2006 Pearson Addison-Wesley. All rights reserved 2-15

Inheritance

A hierarchy of classes.

• Define properties and behavior that is shared by all kinds of vehicle inside base class vehicle for only once .

• Derived classes will add to or revise what they inherited

• The instance of the derived class is also an instance of the base class

© 2006 Pearson Addison-Wesley. All rights reserved 2-16

Inheritance

public class Student

{ private Name studentName; private String studentId;

//method definition…

} public class CollegeStudent extends Student

{ private int year; private String degree;

// method definition…

}

© 2006 Pearson Addison-Wesley. All rights reserved 2-17

Access Scope

Fig. 2-5 Public, private, protected, and package access of the data fields and methods of Base class C.

Accessing Inherited Data Fields

• Private data field in base class

– Not accessible by name within definition of a method from another class – including a derived class

– Still they are inherited by the derived class

• Derived classes must use public methods of the base class

• Note that private methods in a base class are also unavailable to derived classes

– Cannot invoke private methods in base class by name

– But usually not a problem, the inherited public method can be called and the public method can call not inherited private method in the base class. In addition, private methods are used only for utility duties within their class

© 2006 Pearson Addison-Wesley. All rights reserved 2-19

Inheritance

public class Student

{ private Name studentName; private String studentId;

//method definition…

} public class CollegeStudent extends Student

{ private int year; private String degree;

// method definition…

}

• After defining the derived class, need to instantiate its object.

• How to initialize the inherited private data fields in base class?

© 2006 Pearson Addison-Wesley. All rights reserved 2-20

Calling the Base Class's Constructor

• Constructors usually initialize data fields

• In a derived class

– The constructor must call the base class constructor

• Can use the reserved word

super

as a name for the constructor of the base class

– When super is used, it must be the first action in the derived constructor definition

– Must not use the name of the constructor

© 2006 Pearson Addison-Wesley. All rights reserved 2-21

Calling the Base Class's Constructor public CollegeStudent(Name studentName, String studentId, int graduationYear, String degreeSought)

{ super (studentName, studentId); year = graduationYear; degree = degreeSought;

}

© 2006 Pearson Addison-Wesley. All rights reserved 2-22

Protected Access

• A method or data field that is modified by protected can be accessed by name only within

– Its own class definition C

– Any class derived from C

– Any class within the same package as C

© 2006 Pearson Addison-Wesley. All rights reserved 2-23

Multiple Inheritance

• Some languages allow programmer to derive class

C

from classes

A

and

B

• Java does not allow this

– A derived class can have only one base class

• Multiple inheritance can be approximated

– By chain of inheritance

– A derived class can have multiple interfaces

© 2006 Pearson Addison-Wesley. All rights reserved 2-24

Object Types of a Derived Class

• Given :

– Class CollegeStudent ,

– Derived from class Student

• Then a CollegeStudent object is also a

Student object

• An object of a derived class is also an object of the base class

– Instance of derived class can invoke a method defined in base class.

– Everything works for objects of an base class also works for objects of any derived class.

© 2006 Pearson Addison-Wesley. All rights reserved 2-25

Overriding Methods

• Revising instead of adding…

• When a derived class defines a method with the same signature as in base class

– Same name

– Same return type

– Same number, types of parameters

• Objects of the derived class that invoke the method will use the definition from the derived class

• It is possible to use super in the derived class to call an overridden method of the base class

© 2006 Pearson Addison-Wesley. All rights reserved 2-26

Overriding Methods

The method toString in CollegeStudent overrides the method toString in Student

© 2006 Pearson Addison-Wesley. All rights reserved 2-27

Overloading a Method

• When the derived class method has

– The same name

– The same return type … but …

– Different number or type of parameters

• Then the derived class has available

– The derived class method … and

– The base class method with the same name

• Java distinguishes between the two methods due to the different parameters passed by arguments.

© 2006 Pearson Addison-Wesley. All rights reserved 2-28

Overloading a Method

Example:

• In base class Student:

– public void setStudent(Name studentName, String studentId)

• In derived class CollegeStudent:

– public void setStudent(Name studentName, String studentId, int graduationYear, String degreeSought)

An instance of Student can only call the Student’s version, but an instance of CollegeStudent can invoke either method .

© 2006 Pearson Addison-Wesley. All rights reserved 2-29

Abstract Classes and Methods

• Some base classes are not intended to have objects of that type

– The objects will be of the derived classes

• Declare that base class to be abstract, prevents client from creating objects of this class public abstract class ClassnameA

{ . . . }

• The designer often specifies methods of the abstract class without a body public abstract void doSomething();

– This requires all derived classes to implement this method in an appropriate way since base class cannot write a method for future class. If there is at least one abstract method, the class should be abstract. Otherwise, the object will have no implementation for some method.

© 2006 Pearson Addison-Wesley. All rights reserved 2-30

Polymorphism

• Comes from Greek word means “many forms”

• When one method name in an instruction can cause different actions

– according to the type of objects that the reference points to at the time of method invocation

• Example

UndergradStudent ug = new UndergradStudent(. . .);

Student s = ug; // s and ug are aliases s.displayAt(2); ug.displayAt(4);

© 2006 Pearson Addison-Wesley. All rights reserved 2-31

Polymorphism

• Which displayAt is called …

– Depends on the type of invoking object the variable references (run time), and is not determined by the type of the variable naming the object (compile time)

UndergradStudent ug = new UndergradStudent(. . .);

Student s = ug; // s and ug are aliases s.displayAt(2); ug.displayAt(4);

The object still remembers it is of type UndergradStudent

The variable s is another name for an undergraduate object.

© 2006 Pearson Addison-Wesley. All rights reserved 2-32

Polymorphic variable

• A variable’s static type is the type that appears in its declaration .

• Static type is fixed and determined when the code is compiled.

• They do not have to be the same but should be compatible.

• The type of object that a variable references during execution is called dynamic type .

• Dynamic type can change as execution progresses.

• Reference variable is called polymorphic variable, since its dynamic type can differ from its static type and change during execution.

© 2006 Pearson Addison-Wesley. All rights reserved 2-33

Dynamic Binding

• The process that enables objects to …

– Use different method actions

– For the same method name

• Depending on the object’s type determined at execution time not compilation time.

• Objects know how they are supposed to act

– When an overridden method is used …

© 2006 Pearson Addison-Wesley. All rights reserved 2-34

Dynamic Binding

UndergradStudent ug = new UndergradStudent(. . .);

Student s = ug; // s and ug are aliases s.displayAt(2);

GradStudent g = new GradStudent(. . .); s = g; s.displayAt(2);

© 2006 Pearson Addison-Wesley. All rights reserved 2-35

Exercises

Consider the following Java statements: public static Student s1 = new GraduateStudent(...); public static void main(String args[])

{

Student ug = new UndergradutateStudent(...);

GraduateStudent grad = new GraduateStudent(...); winner(ug);

} public static void winner(Student pupil)

{

System.out.println(“And the winner is “); pupil.displayAt(1);

} a. What are the static and dynamic types for each variable when the code is executed? (s1, ug, grad, and pupil) b. If we change the call winner(ug) to winner(s1), what are the resulting static and dynamic types for pupil

© 2006 Pearson Addison-Wesley. All rights reserved 2-36

Exercises

Imagine two classes, A and B.

Class A has a private data field theData and the following methods: public void w(); public void x(); protected void y(); private void z();

Class B extends class A and has the following methods: public void x(); protected void r(); private void s();

Suppose that the client declares instances of these classes as follows:

A inA = new A();

B inB = new B(); a. Which of the objects inA and inB can the client use to directly access the field theData?

b. Which of these objects can the client use to invoke the method w?

c. Which of these objects can the client use to invoke the method y?

d. Which method definitions can invoke the method y?

e. Which method definitions can invoke the method r?

f. Which method definitions can invoke the method z?

g. Which version of the method x does inB.x() invoke? h. Which methods are available to clients of B, namely inB?

© 2006 Pearson Addison-Wesley. All rights reserved 2-37