part v: object-oriented programming with javausers.encs.concordia.ca/~bentahar/comp348/part 5...

38
1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles of COMP 348/1: Principles of Programming Languages Summer 2013 Acknowledgement: Dr. C. Constantinides Concordia University Procedural programming Traditionally, programs were thought of as sequences of statements. Procedural programming: Data and procedures are separate entities. 2 Main idea behind procedural programming Identify tasks to be performed, then break them down into subtasks (stepwise refinement). Top-down approach. Write procedures to solve simple tasks and combine 3 them into more sophisticated procedures. Bottom-up approach. function function function function Global data Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) sees programs as collections of interacting modules. Data (state) and functions that manipulate it (behavior) are encapsulated in a module (an object). 4 Linguistic objects can directly model objects in the real world. Object Object Object message message message

Upload: others

Post on 30-Jul-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

1

Part V:Object-Oriented Programming

with Java

COMP 348/1: Principles ofCOMP 348/1: Principles of Programming Languages

Summer 2013

Acknowledgement: Dr. C. Constantinides

Concordia University

Procedural programming

• Traditionally, programs were thought of as sequences of statements.

• Procedural programming: Data and procedures are separate entities.

2

p

Main idea behind procedural programming

• Identify tasks to be performed, then break them down into subtasks (stepwise refinement). Top-down approach.

• Write procedures to solve simple tasks and combine

3

p pthem into more sophisticated procedures. Bottom-up approach.

function

function

function

function

Global data

Object-Oriented Programming (OOP)

• Object-Oriented Programming (OOP) sees programs as collections of interacting modules.

• Data (state) and functions that manipulate it (behavior) are encapsulated in a module (an object).

4

p ( j )

• Linguistic objects can directly model objects in the real world.

ObjectObject

Object

message message

message

Page 2: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

2

Agent computing

• An agent is a computer system that is situated in some environment, and that is capable of autonomous action in this environment in order to meet its design objectives“ (Wooldridge and

5

Jennings,1994)

• Reactivity, pro-activeness, social ability• Agents are equipped with beliefs, goals and can

have commitments• Flexible and intelligent computing.• Agents are implemented as objects (Jack, jade

and Jadex)

Web services computing

• SOA is a programming style

• A SOA application is a composition of services

• A ‘service’ is a building bl k/ it f SOA

ServiceRegistry

RegisterFind

6

block/unit of an SOA

• Service encapsulates a business process

• A Service Provider registers services

• Service consumption involves Find-Bind-Execute pattern

ServiceConsumer

ServiceProvider

RegisterFind

BindExecute

Figure 1. SOA Elements

OOP: Classes and objects

• A class is a template from which objects may be created.– Can have any number of instances (objects).

• An object contains state (data fields or variables) and behavior (methods, or functions).

7

( )

• Methods of an object collectively characterize its behavior.– Methods can only be invoked by sending messages to an object.– Behavior is shared among objects.

Identifying objects and their state

public class Book {String author;String title;String year;...

}

8

• author, title, year are instance variables; they hold data.

• They are of type String, i.e. they can hold textual data.

• The state of the object is composed of a set of attributes (or fields), and their current values.

Page 3: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

3

Object behavior: methods

public class Book {…public void display () {System.out.println ("Author: " + author + "\n" +

"Title: " + title + "\n" +"Year: " + year + "\n");

}}

9

}}

• Method display() is of type void, because it does not return any value.

• The body of a method lies between { and } and defines some computation to be done.

• The behavior of the object is defined by a set of methods, which may access or manipulate the state.

Object initialization: constructor methods

public class Book {…Book (String author, String title, String year) {

this.author = author;this.title = title;

10

this.year = year;}}

• Book() is a special method, called the constructor of the class.

• A constructor is a special method, which automatically initializes an object immediately upon creation.– It has the exact same name as the class in which it resides.– A constructor has no return type, not even void.

Field initialization during construction

public class Book {String author;String title;String year;Book (String author, String title, String year) {

11

this.author = author;this.title = title;this.year = year;

}…}

1. All data fields are set to their default values (zero, false or null).2. The data fields with initializers are set, in the order in which they

appear in the class definition.3. The constructor body is executed.

Field shadowing

• The statementString author = author in the constructor that

shadows the data field author defines a new local variable author.

Aft th t t i fi i h d th l l i bl

12

• After the constructor is finished, the local variables are forgotten and the data field author is still null (as it was before entering the constructor)

Page 4: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

4

Creating a Book instance (object)

public class TestV01 {static public void main (String args[]) {

Book MyBook = new Book ("Timothy Budd", "OOP", "1998");

13

}}

• The new operator creates an instance of a class (object).

Implementing methods

• What is wrong with the following code?

public class PurchaseOrder {...public double calculateTotal (double price,

i t tit ) {

14

int quantity) {if (quantity >= 0)

return price * quantity;}}

• The path quantity < 0 is not terminated by a returnstatement. As a result, a compilation error will occur.

Implementing methods

• What is wrong with the following code?

public class PurchaseOrder {...public double calculateTotal (double price,

int quantity) {

15

q ydouble total;if (quantity >= 0)

return Price * quantity;return total;

}}

• Local variables are not automatically initialized to their default values.

• Local variables must be explicitly initialized.• The code will cause a compilation error.

Parameter passing

• Objects are passed by reference.• Primitive types are passed by value (i.e. modifications

are made on copies of the actual parameters).• In order for a parameter of primitive type to serve as a

reference parameter, it must be wrapped inside a class.

bli l f {

16

public class IntRef {public int val;public IntRef(int i) {val = i;}

}

public class C {public void inc(IntRef i) {i.val++;}

}

C c = new C();IntRef k = new IntRef(1); // k.val is 1c.inc(k); // now k.val is 2

Page 5: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

5

Parameter passing

• The parameter designator final indicates that the parameter cannot be assigned a new value in the body of the method.

• However, if the parameter is of reference type, it is allowed to modify the object (or array) referenced by the fi l t

17

final parameter.

void aMethod(final IntRef i) {…i = new IntRef(2); // not allowed

}

void aMethod(final IntRef i) {…i.val++; // ok

}

Object values are really pointers

class Employee {public Employee(String n, double s) {

_name = n;_salary = s; }

public double salary() {return _salary; }

18

public void raiseSalary(double percent) {_salary *= 1 + percent / 100;}

private String _name;private double _salary; }

Employee harry = new Employee(“Harry”, 35000);

Object values are really pointers

class Employee {public void swapSalary(Employee b) {double temp = _salary;_salary = b._salary;b._salary = temp; // has effect outside

// this function

19

}...}

• If this method is called as harry.swapSalary(charley) then the salaries of harry and charley are swapped.

Type signature

• The type signature of a method (or constructor) is a sequence that consists of the types of its parameters.

• For example:

public class Book {

20

...Book (String author, String title, String year) {...}public void display () {...}}Book - (String, String, String)display - ()

• Note that the return type, parameter names, and final designations of parameters are not part of the signature. Only parameter type and order is significant.

Page 6: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

6

Static features: A first view

• Static features are used outside of the context of any instances.

• Static blocks: As soon as the class is loaded, all static

21

blocks are run before main()

• Static methods:

– Static methods can be accessed from any object;

– They can be called even without a class instantiation, e.g. main()

Example

public class staticTest {static int a = 3;static int b;static void method (int x) {

System.out.println(“x = “+ x);}

22

static {System.out.println(“Inside static block.");b = a * 4;System.out.println(b);

}public static void main (String[] args) {

method(42);}

}Inside static block.12x = 42

Accessing static features

• Instance variables and methods can be accessed only through an object reference (You cannot access instance variables or call instance methods from static methods.)

• Static variables and methods may be accessed through ith bj t f th l

23

either an object reference or the class name.

objectReference.staticMethod(parameters)objectReference.staticVariable

ClassName.staticMethod(Parameters)ClassName.staticVariable

Example

public class Counter {public Counter() { howMany++; }public void reset() { value = 0; }public int get() { return value; }public void click() { value = (value + 1) % 100; }

24

public static int howMany() {return howMany;}private int value;private static int howMany = 0;}

• Each time a Counter object is created, the static variable howMany is incremented.

• Unlike the field value, which can have a different value for each instance of Counter, the static field howManyis universal to the class.

Page 7: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

7

Example

• The following (modified) version of Counter is illegal.

public class Counter2 {public Counter2() { howMany++; }public static void reset() { value = 0; }public int get() { return value; }public void click() {

25

public void click() {value = (value + 1) % 100; }

public static int howMany() {return howMany;}private int value;private static int howMany = 0;

}// ERROR! value is not static.public static void reset() { value = 0; }

Example

public class Point {public double x, y;private int moveCount;static private int globalMoveCount;public void move (double dx, double dy) {

x += dx; y += dy;

26

moveCount++;globalMoveCount++; }

public int getMoveCount() {return moveCount; }

static public int getGlobalMoveCount() {return globalMoveCount; }

}

Example

Point p1 = new Point();Point p2 = new Point();p1.move(20.0, 10.0);p1.move(10.0, 20.0);p2.move(10.0, 10.0);System.out.println(p1.getMoveCount());

27

// moveCount of p1 is 2System.out.println(p2.getMoveCount());// moveCount of p2 is 1System.out.println(p1.getGlobalMoveCount());// globalMoveCount is 3System.out.println(p2.getGlobalMoveCount());// globalMoveCount is 3System.out.println(Point.getGlobalMoveCount());// globalMoveCount is 3

Initialization of static fields

• With their default values as instatic private int globalMoveCount;

• With an explicit initializer as inpublic class Point {

28

...static private int globalMoveCount = 0;...}

• By the static initialization blockpublic class Point {

...static private int globalMoveCount;static {globalMoveCount = 0;}}

Page 8: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

8

Singleton classes

• Singleton classes are not allowed more than one instance at a time.

• Clients are prohibited from creating an instance of Singleton.

• The only way for clients to obtain an instance of Singleton is to use the static method getInstance()

29

Singleton is to use the static method getInstance()

public class Singleton {public static Singleton getInstance() {

if (theInstance == null) theInstance = new Singleton();

return theInstance; }private Singleton() {...}…

private static Singleton theInstance = null;}

Sending messages

• A message represents a command sent to an object (recipient or receiving object, or receiver of the message) to perform an action by invoking one of the methods of the recipient.

30

p

• A message consists of the receiving object, the method to be invoked, and (optionally) the arguments to the method: object.method(arguments);

public class TestV01 {static public void main(String args[]) {

Book MyBook = new Book ("Timothy Budd","OOP", "1998");

MyBook.display();

Defining a Book class

31

MyBook.display();}}

Defining a Journal classpublic class Journal {

String editor;String title;String year;String month;Journal (String editor, String title, String year,

String month) {

32

this.editor = editor;this.title = title;this.year = year;this.month = month;}

public void display () {System.out.println ("Editor: " + editor + "\n" +

"Title: " + title + "\n" +"Year: " + year + "\n" +"Month: " + month + "\n");}}

Page 9: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

9

Extending classes: Inheritance relationships

• Inheritance defines a relationship between classes.

• Inheritance: a mechanism for reusing the implementation and extending the functionality of superclasses.

All bli d t t d b f th l

33

• All public and protected members of the superclass are accessible in the extended class.

• When class C2 inherits from (or extends) class C1, class C2 is called a subclass or an extended class of C1.

• C1 is the superclass of C2.

Inheritance

• A subclass can extend the capability of its superclass.

• The subclass inherits features from its superclass, and may add more features.

34

• A subclass can be viewed as a specialization of its superclass.

• Every instance of a subclass is an instance of a superclass, but not vice-versa.

Classes and types

• Each class defines a type. All instances of the class constitute the set of the legitimate values of that type.

• As every instance of a subclass is also an instance of its superclass, the type defined by the subclass is a subset of the type defined by its superclasses.

35

• The set of all instances of a subclass is included in the set of all instances of its superclass.

• For example, lines and rectangles are shapes.

Shape

Line Rectangle

Abstract classes

• Abstract classes cannot be directly instantiated.

• Any class that contains abstract methods must be declared abstract.

36

• Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or itself be declared abstract.

Page 10: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

10

Defining abstract parent class PrintedItem

public abstract class PrintedItem {String title;String year;PrintedItem (String title, String year) {

this.title = title;this.year = year;

}

37

}public abstract void display ();

}

Illustrating the inheritance hierarchy of the library information system

PrintedItem

titleyear

display()

38

Book

author

Journal

editormonth

Initialization of subclass

• The initialization of a subclass consists of two phases:

1. The initialization of the fields inherited from the superclass (one of the constructors of the superclass is invoked).

2. The keyword super refers directly to the constructor of the superclass.

3 Th i iti li ti f th fi ld d l d i th t d d l

39

3. The initialization of the fields declared in the extended class.

public class Book extends PrintedItem {String author;Book (String author, String title,

String year) {super(title, year);this.author = author;}…}

Order of field initialization

• The following order of initialization applies to the fields in both the superclass and the extended class:

1. The fields of the superclass are initialized, using explicit initializers or the default initial values.

40

initializers or the default initial values.

2. One of the constructors of the superclass is executed.

3. The fields of the extended class are initialized, using explicit initializers or the default initial values.

4. One of the constructors of the extended class is executed.

Page 11: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

11

Order of field initialization

public class Super {int x = ...; // 1public Super() {

x = ...; // 2}...}

41

public class Extended extends Super {int y = ..; // 3public Extended() {

super();y = ...; // 4

...}

Redefining class Journal

public class Journal extends PrintedItem {String editor;String month;Journal (String editor, String title, String year,

String month) {super(title, year);this editor = editor;

42

this.editor = editor;this.month = month;

}public void display () {

...}

}

Creating Book and Journal objects and sending messages

public class TestV04 {static public void main (String args[]) {Book Book1 = new Book ("Timothy Budd", "OOP", "1998");Book Book2 = new Book ("Mark Grand", "Design Patterns",

"2000");Journal Journal1 = new Journal ("David Parnas",

43

"Computer Journal", "2003", "November");Journal Journal2 = new Journal ("Edger Dijkstra",

"Electronic Journal", "2004", "January");Book1.display();Book2.display();Journal1.display();Journal2.display();}}

Illustration

Author: Timothy BuddTitle: OOPYear: 1998

displayBook

author

Author: Mark Grand

display

44

Journal

editormonth

Author: Mark GrandTitle: Design PatternsYear: 2000

Editor: David ParnasTitle: Computer JournalYear: 2003Month: November

display

Editor: Edger DijkstraTitle: Electronic JournalYear: 2004Month: January

display

Page 12: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

12

Type signatures revisited

• Recall that the type signature of a method or constructor is a sequence that consists of types of its parameters.

• The parameter order is significant.• The return type, parameter names, and final

designations of parameters are not part of the signature.

45

g p p g

Method Type signature

String toString() ()void move(int dx, int dy) (int, int)void move(final int dx, final int dy) (int, int)void paint(Graphics g) (Graphics)

Method overloading

• If two methods or constructors in the same class (or related classes) have different type signatures, then they may share the same name; that is, they may be overloaded on the same name.

• The name of the method is said to be overloaded with

46

The name of the method is said to be overloaded with multiple implementations.

• When an overloaded method is called, the number and the types of the arguments are used to determine the signature of the method that will be invoked.

• Overloading is resolved at compile time.

Example: class Account

public class Account {Account() {this.balance = 0;}Account(String name, String account, double balance){

this.name = name;this.account = account;this.balance = balance;

47

}public void getBalance () {

System.out.println (balance);}public void deposit (double amount) {

balance = balance + amount;}public void withdraw (double amount) {

balance = balance - amount;}String name;String account;double balance;

}

Instantiating class Account

public class Account {Account () {...}Account (String name, String account,

double balance) {…}...}

public class AccountTest {

48

p {static public void main (String args[]) {

Account a = new Account("bob", "BOB2003", 1000);a.deposit(150);a.withdraw(50);a.getBalance();

a.withdraw(2000);a.getBalance();

}}

1100.0-900.0

Page 13: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

13

Introducing class SavingsAccount

public abstract class Account {..}

public class SavingsAccount extends Account {SavingsAccount(String name, String account,

double balance){super(name, account, balance);

49

}public void withdraw(double amount){

if (amount > balance)System.out.println ("ERROR");

elsesuper.withdraw(amount);

}}

Executing the code

public class AccountTest {static public void main (String args[]) {

SavingsAccount s = new SavingsAccount ("Joe Smith","JOESMITH2004", 1000);

s.getBalance();s.withdraw(2000);

50

( );s.getBalance();

}}1000.0ERROR1000.0

Overloading methods in a superclass

• You might overload a superclass method to provide additional functionality.

• When writing a method that has the same name as a method in a superclass double check the return values

51

method in a superclass, double check the return values and the argument lists to make sure that you are overloading or overriding as you intended.

Example

public class MyClass {private int anInt = 4;//Overrides toString() in Object class.public String toString() {return "Instance of MyClass. anInt = " + anInt;

}

52

//Overloads toString method name to provide //additional functionality.public String toString (String prefix) {return prefix + ": " + toString();

}}

Page 14: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

14

Encapsulation and information hiding

“Every module … is characterized by its knowledge of a design decision which it hides from all others. Its interface or definition was chosen to reveal as little as possible about its inner workings.”

P C i ti f th ACM 1972

53

Parnas, Communications of the ACM, 1972.

Encapsulation and information hiding

• Encapsulation: enforcement of abstraction barriers; data are packaged with the operations that access it.

• Interface and implementation are separated (information hiding)

54

hiding).

• Implementation details are hidden from clients. A client can access data only by issuing requests for a service.

Encapsulation and information hiding

• The separation of interface and implementation allows the class interface to be mapped to several different implementations.

• The client is concerned with the service to be performed; not with the details of how it is performed.

• Benefits associated with encapsulation and information

55

Benefits associated with encapsulation and information hiding:– Clients cannot execute the wrong code.– Implementation can be modified without affecting the clients, as

long as the interface remains the same. (evolution, and maintenance)

– The less the clients know about the implementation of the module, the looser the coupling between the module and its clients can be.

Cloning

• Cloning refers to returning a copy of oneself.

• Java provides Cloneable interface.

56

• To create a Cloneable class, the programmer must implement the Cloneable interface and can override the clone method.

Page 15: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

15

Example

class MyClass implements Cloneable {

public MyClass() {…}

public Object clone() {

57

return theClone = super.clone();

// creates and return theClone.

}

}

Cloning

• The result of cloning a value must be cast to the actual

type before it can be assigned to a variable.

• Consider the following code to create a clone:

58

Consider the following code to create a clone:

MyClass myObject = new MyClass();

MyClass myObjectClone =

(MyClass)myObject.clone();

An intuitive description of inheritance

• The behavior and data associated with child classes are always an extension of the properties associated with parent classes.

• A child class will be given all the properties of the parent class and may in addition define new properties

59

class, and may in addition define new properties.

• Inheritance is always transitive, so that a class can inherit features from superclasses many levels away.

Method overriding

• A complicating factor in our intuitive description of inheritance is the fact that subclasses can override behavior inherited from parent classes.

• Overriding refers to the introduction of an instance

60

gmethod in a subclass that has the same name, same type signature and same return type of a method in the superclass, but a different implementation.

• The implementation of the method in the subclass replaces the implementation of the method in the superclass.

Page 16: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

16

Example

public class Employee {public Employee (String name, double salary) {

this.name = name;this.salary = salary;

}public void display() {

S t t i tl ("N " + + " S l " +

61

System.out.println ("Name: " + name + ". Salary: " +salary + "\n");

}public void raiseSalary (double byPercent) {

salary = salary + (salary * byPercent / 100);}private String name;private double salary;

}

Example

public class Test {static public void main (String args[]) {

Employee e = new Employee ("Janis Joplin", 1000);e.display();

e raiseSalary(10);

62

e.raiseSalary(10);e.display();

}}

Name: Janis Joplin. Salary: 1000.0

Name: Janis Joplin. Salary: 1100.0

Example

public class Manager extends Employee {public Manager (String name, double salary) {

super(name, salary);}public void raiseSalary (double byPercent) {

63

double bonus = 200;super.raiseSalary (byPercent + bonus);

}}

Example

public class Test {static public void main(String args[]) {

Employee e = new Employee ("Janis Joplin", 1000);e.display();e.raiseSalary(10);e.display();

64

Manager m = new Manager ("John Lennon", 1000);m.display();m.raiseSalary(10);m.display();

}}

Name: Janis Joplin. Salary: 1000.0Name: Janis Joplin. Salary: 1100.0

Name: John Lennon. Salary: 1000.0Name: John Lennon. Salary: 3100.0

Page 17: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

17

Example: Class Point and ColoredPoint

public class Point {Point(double x, double y) {this.x = x; this.y =y; }Point() {this(-1, -1); }double x, y; }

public class ColoredPoint extends Point {

65

public Color color;public ColoredPoint(double x, double y, Color color) {

super(x, y);this.color = color; }

public ColoredPoint(double x, double y) {this(x, y, Color.black); // default}

public ColoredPoint() {color = Color.black;}}

Example: Class Point and ColoredPointpublic ColoredPoint(double x,double y, Color color) {super(x, y);this.color = color;}

x, y are initialized by invoking Point(double, double)

super must be the first statement in thecontructor of the extended class.

Color is initialized in the constructors of ColoredPoint

66

public ColoredPoint(double x, double y) {this (x, y, Color.black);}

public ColoredPoint() {color = Color.black;}

Invokes ColoredPoint(double, double, Color)This must be the first statement in theconstructor.

The no-arg constructor of the superclass isinvoked implicitly.

• If no constructor is defined in the extended class, a no-arg constructor is provided by default.

• The default no-arg constructor will invoke the no-arg constructor of the superclass

67

constructor of the superclass.

• If superclass does not provide a no-arg constructor, an error will occur.

Inheritance hierarchies

• Inheritance does not stop at deriving one layer of classes.

• For example, we can have an Executive class that derives from Manager.

68

Employee

Manager Secretary Programmer

Executive

Page 18: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

18

Inheritance hierarchies

• The collection of all classes extending from a common parent is called an inheritance hierarchy.

• The path from a particular class to its ancestors in the inheritance hierarchy is its inheritance chain e g

69

inheritance hierarchy is its inheritance chain, e.g. Executive – Manager – Employee.

Overriding and hiding

• When a subclass declares a variable or static method that is already declared in its superclass, it is not overriden; it is hidden.

class A {int x;

70

int x;void y() {...}static void z() {...}}

class B extends A {float x; // hidingvoid y() {...} // overridingstatic int z() {...}} // hiding

Overriding versus hiding

• Overriding and hiding are different concepts:

• Instance methods can only be overriden. A method can be overriden only by a method of the same signature and return type.

When an overriden method is invoked the implementation that

71

– When an overriden method is invoked, the implementation that will be executed is chosen at run time.

• Static methods and fields can only be hidden.– When a hidden method or field is invoked or accessed, the copy

that will be used is determined at compile time.– In other words, the static methods and fields are statically bound,

based on the declared type of the variables.

Example

class Point {public String className ="Point";static public String getDescription() {

return "Point";}...}

Hides field of samename

72

class ColoredPoint extends Point {public String className = "ColoredPoint";static public String getDescription() {

return "ColoredPoint";}...}

of Point class.

Hides method ofsame nameof Point class.

Page 19: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

19

• Although both p1 and p2 refer to the same object, the binding of the static methods and fields is based on the declared types of the variables at compile time.

• The declared type of p1 is ColoredPoint, and of p2 is Point.

73

ColoredPoint p1 = new ColoredPoint(10.0, 10.0, Color.blue);

Point p2 = p1;System.out.println(p1.getDescription());System.out.println(p2.getDescription());System.out.println(p1.className);System.out.println(p2.className); ColoredPoint

PointColoredPointPoint

Example

public class Animal {public Animal() {…}public static void hide() {System.out.println("The hide method in Animal.");}

public void override() {System.out.println("The override method in

Animal.");}}

74

public class Cat extends Animal {public static void hide() {

System.out.println("The hide method in Cat.");}public void override() {System.out.println("The override method in Cat.");}

public static void main (String[] args) {Cat myCat = new Cat();Animal myAnimal = (Animal) myCat;myAnimal.hide();myAnimal.override();}}

Example

• The Cat class overrides the instance method in Animalcalled override and hides the class method in Animalcalled hide.

• The main method in this class creates an instance of

75

Cat, casts it to a Animal reference, and then calls both the hide and the override methods on the instance.

• The output from this program is as follows:

The hide method in Animal.The override method in Cat.

Object reference with “this”

• Keyword this is used inside instance methods to refer to the receiving object of the methods, i.e. the object instance through which the method is invoked.

• Keyword this may not occur inside static methods

76

• Keyword this may not occur inside static methods.

• The two common uses of this are:1. To pass the receiving object instance as a parameter

2. To access instance fields shadowed, or hidden, by local variables.

Page 20: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

20

Example

public class Faculty {protected Department dept;protected String name;public Faculty(String n, Department d) {

name = n; dept = d;}public Department getDepartment() {

return dept;}...}

77

return dept;}...}

public class Department {protected String name;protected Faculty facultyList[] = new Faculty[100];protected int numOffaculty = 0;public Department(String n) {name = n;}public void newFaculty(String name) {

facultyList[numOffaculty++] = new Faculty(name, ?);

}...} ?=this

Example

• If a faculty member a occurs in the facultyList of department d, then a.dept should refer to d.

• This consistency is maintained in the newFaculty()method by passing the this reference the department

78

method by passing the this reference - the department to which the new faculty belongs - as the parameter to the constructor of the Faculty class.

Accessing shadowed fields

• A field declared in a class can be shadowed, or hidden, inside a method by a parameter or a local variable of the same name.

• The hidden variable can be accessed as this.var

public class MyClass {

79

public class MyClass {int var;void method1() {

// local variable shadows instance variablefloat var;...}

void method2(int var) {// var also shadows the instance variable

}}

Preventing inheritance

• Use the final modifier in the class definition to prevent a class from ever becoming a parent class.final class MyClass {…}

• You can also make a specific method in a class final in which case no class can override this method

80

which case no class can override this method.

• All methods in a final class are automatically final.

• The modifier final is the opposite of abstract.– When applied to a class, it implies that the class cannot be

subclassified.– When applied to a method, the keyword indicates that the

method cannot be overriden.

Page 21: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

21

Subtype relationships

• The subset relation between the value set of types is known as the subtype relationship.

• Type T1 is a subtype of Type T2 if every legitimate value of T1 is also a legitimate value of T2. In this case, T2 is the supertype of T1

81

the supertype of T1.

• The inheritance relationship among classes is a subtype relationship.

• A value of a subtype can appear wherever a value of a supertype is expected.– An instance of a subclass can appear wherever an instance of a

superclass is expected.

Subtype relationships

• The conversion of a subtype to one of its supertypes is called widening; It is carried out implicitly whenever necessary.

• In other words, a reference to an object of class C can be

82

implicitly converted to a reference to an object of one of the superclasses of C.

• The conversion of a supertype to one of its subtypes is called narrowing.

• Narrowing of reference types requires explicit casts.

Abstract classes and subtypes

• The class hierarchy that results from the use of inheritance creates a related set of types.

• Instances of any subclass of a given superclass may be referenced by a superclass variable.

83

y p

• Principle of type substitutability: A subtype can be used anywhere the supertype is expected.

• This principle holds because all the methods needed for the superclass are available for the subclass object.

Example

• An object of type Counter may be referenced by a variable of type AbstractCounter.

abstract public class AbstractCounter {abstract public void click();public int get() {return value;}

84

public int get() {return value;}public void set(int x) {value = x;}public String toString() {

return String.valueOf(value);}protected int value;}

public class Counter extends AbstractCounter {public void click() {

value =(value + 1) % 100;}}

Page 22: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

22

Example

• The following code fragment shows a method that expects a parameter that is a subclass of AbstractCounter:

void sampleMethod (AbstractCounter counter) {

85

...counter.click();...}

Polymorphic assignments

• The type of the expression at the RHS of an assignment must be a subtype of the type of the variable at the LHS of the assignment.

• For example if class E extends class B any instance of

86

• For example, if class E extends class B, any instance of E can act as an instance of B.

First example of polymorphic assignment

class Student {public Student (String name) {this.name = name;}public String toString() {return "Student: " + name;}protected String name;

}

87

class Undergraduate extends Student {public Undergraduate (String name) {super(name);}public String toString() {

return "Undergraduate student: " + name;}}

class Graduate extends Student {public Graduate(String name) {super(name);}public String toString() {

return "Graduate student: " + name;}}

Type checking

Student student 1, student2;

student1 = new Undergraduate();student2 = new Graduate();

Graduate student3;

88

student3 = student2;

• In the last statement, the RHS (of type Student) is not a subtype of the LHS (of type Graduate).

Page 23: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

23

Explicit casting

• Type checking is carried out at compile time and it is based on the declared types of variables.

• An explicit cast is necessary here:

t d t3 (G d t ) t d t2 // d ti

89

student3 = (Graduate) student2; // downcasting

Validity of explicit casting

• The validity of explicit cast is checked at run-time.

• A run-time check will be performed to determine whether student2 actually holds an object that is an instance of Graduate or its subclasses.

90

student3 = (Graduate) student1; //compilation ok

• The statement will throw a run-time exception as student1 actually holds an instance of Undergraduate (which is not a subtype of Graduate)

• In order to prevent a run-time exception, use the instanceof operator:

• The expression exp instanceof Type returns a boolean indicating whether exp is an instance of a class or an interface named Type

91

or an interface named Type.

if (student1 instanceof Graduate) {Graduate gradStudent = (Graduate) student1;

}else {

// student1 is not a graduate student}

Validity of method invocation

• Let’s assume that class Graduate defines a method getResearchTopic() that is not defined in class Student.

Student student1 = new Graduate();...

92

...student1.getResearchTopic(); // error

• The declared type of student1 is Student, not Graduate, even though Student1 holds an instance of Graduate.

• The validity of method invocation is checked statically (at compile time) and it is based on the declared types of variables, not the actual classes of objects.

Page 24: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

24

Validity of method invocation

• Thus, student1 must be downcast to Graduate before invoking getResearchTopic() :

Student student1 = new Graduate();…if (student1 instanceof Graduate) {

93

if (student1 instanceof Graduate) {Graduate gradStudent = (Graduate) student1;

gradStudent.getResearchTopic();…

}…}

Validity of method invocation

• Why not declare student1 to be Graduate in the first place?

– student1 may be a parameter; The actual object referred to by student1 may have been created in some other part of the program

94

program.

– student1 may be an element of a collection (see later).

Polymorphic method invocation

• Instance method toString() is overriden in both subclasses.

• The particular implementation of toString() cannot be determined at compile time:

95

Student student;// student is asigned some valuestudent.toString();

• The implementation to be invoked depends on the actual class of the object referenced by the variable at run-time (and not the declared type of the variable). This is called polymorphic method invocation.

Dynamic binding

• For a polymorphic method invocation var.m() dynamic binding proceeds as follows:

currentClass = the class of the object referenced by var.while (inheritance chain not exhausted)

96

if (method m() is implemented in currentClass)then

the implementation of m() in currentClass is invoked.break

elsecurrentClass = the superclass of currentClass;

Page 25: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

25

Example on polymorphic assignment

StudentCourse

Student[] studentsint count

* *

97

Undergraduate Graduate

int countstatic final int CAPACITY

void enroll (Student s)void list()

public class Course {public void enroll(Student s) {

if (s != null && count < CAPACITY)// polymorphic assignment students[count++] = s;

}

98

public void list() {for int i = 0; i < count; i++) // polymorphic invocationSystem.out.println (students[i].toString());

}protected static final int CAPACITY = 40;protected Student students[] = new Student[CAPACITY];protected int count = 0;

}

Cource c = new Course();c.enroll(new Undergraduate(“John”);c.enroll(new Graduate(“Mark”);c.enroll(new Undergraduate(“Jane”);c list();

99

c.list();

Undergraduate student: JohnGraduate student: MarkUndergraduate student: Jane

More on polymorphism

• What happens when you send a message to a subclass?

1. The subclass checks whether or not it has a method with that name and with exactly the same parameters.

100

2. If so, it uses it.

3. If not, the parent class becomes responsible for handling the message and looks for a method with that name and those parameters. If so, it calls that method.

– This message handling can continue moving up in the inheritance chain until a matching method is found or until the inheritance chain is exhausted.

Page 26: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

26

Dynamic method dispatch

• When you call a method using the dot operator on an object reference…

– The declared type of the object reference is checked at compile time to make sure that the method you are calling

101

compile time to make sure that the method you are calling exists in the declared class.

– At runtime, the object reference could be referring to an instance of some subclass of the declared reference type.

• Java uses the actual instance to decide which method to call in the event that the subclass overrides the method being called.

Example: Dynamic method dispatch

class A {void callme() {System.out.println(“Inside A”);}}

class B extends A {void callme() {System.out.println(“Inside B”);}}

102

class Dispatch {public static void main (String args[]) {

A a = new B();a.callme();}}

• Java compiler: has to verify that indeed A has a method named callme()

• Java runtime: notices that the reference is actually an instance of B, so it calls B’s callme() method instead of A’s.

Interfaces

• An interface provides an encapsulation of abstract methods and constants. The general form of an interface isinterface name {

return-type method-name1(parameter-list);type final-varname = value;

103

}

• A class may implement one or more interfaces. A class that implements an interface has the following general form:class classname [extends superclass]

[implements interface0[, interface1…] {

class body}

Implementing interfaces

• Interfaces declare features but provide no implementation.

• Interface methods cannot be static.• An interface can extend other interfaces (not classes).• Classes that implement an interface should provide

implementation for all features (methods) declared in the

104

implementation for all features (methods) declared in the interface.

• Java allows only single inheritance for class extension but multiple inheritance for interface extension.

interface MyInterface {// an abstract methodvoid aMethod (int i); }

class MyClass implements MyInterface {public void aMethod(int i) {…} }

Page 27: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

27

Interfaces and types

• Each interface defines a type.• The interface extension and implementation are also

subtype relations.• Let us define the complete subtype relations in Java:

– If class C1 extends class C2, then C1 is a subtype of C2.

105

y– If interface I1 extends interface I2, then I1 is a subtype of I2.– If class C implements interface I, then C is a subtype of I.– For every interface I, I is a subtype of Object (the parent class

of the entire Java class hierarchy).– For every type T (reference or primitive type) T[] is a subtype of Object.

– If type T1 is a subtype of T2, then T1[] is a subtype of T2[].

A first example using interfaces

interface Callback {void callback(int param);}

class Client implements Callback {void callback (int p) {

System.out.println (“callback called + with “ + p);}

106

System.out.println ( callback called + with + p);}void callme() {

System.out.println (“Inside client”);}}

class TestIface {public static void main (String args[]) {Callback c = new Client();c.callback(42);}}

Interfaces and types

• You can declare variables as object references, which use an interface as the type rather than a class.

• Any instance of any class which implements the declared interface may be stored in such a variable.

107

• Variable c was declared to be of interface Callback, yet it was assigned an instance of Client.

• This way, c can only be used to access the callback() method, and not any of the other features of the Client class.

A second example using interfaces

• Implementing multiple interfaces allows a class to assume different roles in different contexts.

interface Student {float getGPA();

interface Employee {float getSalary();

108

float getGPA();...}

public class FullTimeStudentimplements Student {

public float getGPA() {...}

protected float gpa;...}

float getSalary();...}

public class FullTimeEmployeeimplements Employee {

public float getSalary() {...}

protected float salary;...}

Page 28: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

28

• The StudentEmployee class is a subtype of both Student and Employee.

• Instances of StudentEmployee can be treated either as students or as employees.

public class StudentEmployee

109

public class StudentEmployeeimplements Student, Employee {

public float getGPA() {...}public float getSalary() {...}protected float gpa;protected float salary;...

}

• In one context, a student employee can be viewed as a Student:

Student[] students = new Student[…];

students[0] = new FullTimeStudent();

110

students[0] = new FullTimeStudent();

// studentEmployee as a Student

students[1] = new StudentEmployee();

// …

for (int i = 0; i < students.length; i++) {

.. students[i].getGPA()...

}

• In the other context, a student employee can be viewed as an Employee:

Employee[] employees = new Employee[…];

employees[0] = new FullTimeEmployee();

111

employees[0] = new FullTimeEmployee();

// studentEmployee as Employee

employees[1] = new StudentEmployee();

...

for (int i = 0; i < employees.length; i++) {

.. employees[i].getSalary()...

}

• Creating full-time student and employee classes:

public class StudentImpl implements Student {public float getGPA() {…}protected float gpa;

112

}

public class EmployeeImpl implements Employee {public float getSalary() {…}protected float salary;

}

Page 29: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

29

• The implementation in StudentImpl and EmployeeImpl can be directly reused in the full-time student and employee classes by class extension:

public class FulltimeStudent extends StudentImpl{…}

113

public class FulltimeEmployee extends EmployeeImpl{…}

Delegation

• In addition, a student employee class can be implemented as follows to reuse the implementation in StudentImpl and EmployeeImpl:

public class StudentEmployeeimplements Student, Employee {

114

implements Student, Employee {public StudentEmployee() {

studentImpl = new StudentImpl();employeeImpl = new EmployeeImpl(); ... }

public float getGPA() {return studentimpl.getGPA();} // delegation

public float getSalary() {return employeeImpl.getSalary();} //delegation

protected StudentImpl studentImpl;protected EmployeeImpl employeeImpl; ...}

• The implementation technique used in the getGPA()and getSalary() methods is known as delegation.

• As the name suggests, delegation implies that the method simply delegates the task to another object, studentImpl and employeeImpl, respectively.

• The implementation on the StudentImpl and

115

The implementation on the StudentImpl and EmployeeImpl classes is reused through delegation.

public float getGPA() {return studentimpl.getGPA();

}

public float getSalary() {return employeeImpl.getSalary();

}

Resolving name conflicts among interfaces

• Names inherited from one interface may collide with names inherited from another interface or class.

• How do we resolve name collisions? If two methods have the same name, then one of the following is true:

116

g

1. If they have different signatures, they are overloaded.2. If they have the same signature and the same return type,

they are considered to be the same method.3. If they have the same signature but different return types, a

compilation error will occur.4. If they have the same signature and the same return type

but throw different exceptions, they are considered to be the same method, and the resulting throws list is the union of the two throws lists.

Page 30: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

30

Exampleinterface X {void method1(int i);void method2(int i);void method3(int i);void method4(int i) throws Exception1;}

interface Y {id th d1(d bl d)

Same type signature,different types;Compilation error

Overloaded methods

117

void method1(double d);void method2(int i);int method3(int i);void method4(int i) throws exception2;}

public class MyClass implements X, Y {void method1(int i) {...} // overrides method1 in Xvoid method1(double d) {...} // overrides method1 in Yvoid method2(int i) {...} // overrides method2 in X and Yvoid method4(int i) // overrides method4 in X and Ythrows Exception1, Exception2 {...}}

Constants in interfaces

• Two constants having the same name is always allowed, as they are considered to be two separate constants:

interface X {static final int a = …;}

interface Y {static final double a = …;}

118

interface Y {static final double a …;}

public class MyClass implements X, Y {void aMethod() {

...X.a // the constant in XY.a // the constant in Y

}}

Modifiers and inheritance

• A public feature– can be accessed outside the class definition.– A public class can be accessed outside the package in which itis declared.

• A protected feature– can be accessed within the class definition in which it appears,

119

or– within other classes in the same package, or– within the definition of subclasses.

• A private feature– can be accessed only within the class definition in which it

appears.

• No modifier

Recall…

• A static field is shared by all instances of a class.

• A static method can be invoked even when no instance of the class has been created.

St ti d t fi ld d th d i h it d i th

120

• Static data fields and methods are inherited in the same manner as nonstatic items, except that static methods cannot be overriden.

• Both methods and classes can be abstract. An abstract class cannot be instantiated.

• An abstract method must be overriden by a subclass.

Page 31: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

31

• The modifier final is the opposite of abstract.

– When applied to a class it implies that the class can not be subclassified.

Wh li d t th d it i di t th t th

121

– When applied to a method, it indicates that the method cannot be overriden.

Design hints for inheritance

1. Place common operations and fields in the superclass.

2. Use inheritance to model the “is-a” relationship.

3. Don’t use inheritance unless all inherited methods k

122

make sense.

• Example: Suppose we need a Contractor class.– Contractors have names and hire dates, but they do not

have salaries.– Instead they are paid by the hour.– They also do not stay around for long to get a raise.

• Should Contractor be a subclass of Employee?

class Contractor extends Employee {public Contractor (String name, double wage,

Day hireDay){super(name, 0, hireDay);

123

super(name, 0, hireDay);hourlyWage = wage;}

private double hourlyWage;}

• Now, each Contractor object has both a salary and hourly wage instance variable.

• This will cause a lot of problems when you implement methods to print paychecks and tax forms.

• The contractor/employee relationship fails the “is-a” test.

Forms of inheritance

1. Specialization

2. Specification

3 Construction

124

3. Construction

4. Extension

5. Limitation

6. Combination

Page 32: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

32

Inheritance for specialization

• The new class is a specialized variety of the parent class.

• It satisfies the specifications of the parent class in all relevant aspects.

125

p

• This form always creates a subtype.

• The most common use of inheritance.

• Example: Account – SavingsAccount (overrides method withdraw() not to allow overdrafts).

Inheritance for specification

• Use of inheritance to guarantee that classes maintain a certain common interface.

• Child implements the methods described but not implemented in the parent.

126

p p

• Subclass is a realization of an incomplete abstract specification (parent class defines the operation but has no implementation).

• Supported by two different mechanisms:– Through interfaces– Through inheritance of abstract classes

Inheritance for construction

• A class inherits almost all of its desired functionality from a parent class, even if there is no logical relationship between the concepts of parent and child class.– For example, the concept of a stack and the concept of a

127

For example, the concept of a stack and the concept of a vector have little in common;

– However, from a pragmatic point of view using the vector class as a parent greatly simplifies the implementation of a stack.

• Principle of substitutability does not always hold; subclasses are not always subtypes.

Inheritance for extension

• A child class only adds new behavior to the parent class and does not modify or alter any of the inherited attributes.

• As the functionality of the parent class remains

128

• As the functionality of the parent class remains available and untouched, the principle of substitutability holds and subclasses are always subtypes.

Page 33: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

33

Inheritance for limitation

• The behavior of the subclass is smaller or more restrictive than the behavior of the parent class.

• For example, you can create the class Set in a fashion similar to the way the class Stack is subclassed from vector

129

vector.

• You have to ensure that only Set operations are used on the set, and not vector operations. One way to accomplish this would be to override the undesired methods to generate errors.

• Subclasses are not subtypes.

Inheritance for combination

• When discussing abstract concepts it is common to form a new abstraction by combining features of two or more abstractions.

• The ability of a class to inherit from two or more parent classes is known as multiple inheritance

130

classes is known as multiple inheritance.

• In Java, this is accomplished through a class to extend an existing class and implement an interface.

• It is also possible for classes to implement more than one interface.

Example: Inheritance vs. composition

• Inheritance describes an is-a relation.

class Stack extends Vector {public Object push (Object item) {

addElement(item); return item;}

131

}public Object top() {

return elementAt(size()-1);}public Object pop() {

Object obj = top();removeElementAt(size()-1);return obj;

}}

• Composition describes a has-a relationship.

class Stack {private Vector theData;public Stack() {theData = new Vector();}public boolean empty() {

132

public boolean empty() {return theData.isEmpty();}

public Object push(Object item) {theData.addElement(item); return item;}

public Object top() {return theData.lastElement();}

public Object pop() {Object result = theData.lastElement();theData.removeElementAt(theData.size()-1);return result;

}}

Page 34: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

34

Composition and inheritance contrasted: Substitutability

• Inheritance: Classes formed with inheritance are assumed to be subtypes of the parent class.– As a result, subclasses are candidates for values to

be used when an instance of the parent is expected.

133

• Composition: No assumption of substitutability is present.– With composition, the data types Stack and Vector

are entirely distinct and neither can be substituted in situations where the other is required.

Composition and inheritance contrasted: Ease of use

• Inheritance

– The operations of the new data structure are a superset of the operations of the original data structure on which the new object is built.

To know exactly what operations are legal for the new

134

– To know exactly what operations are legal for the new structure, the programmer must examine the declaration for the original.

– To understand such a class (Stack), the programmer must frequently flip back and forth between declarations.

– For this reason, implementations using inheritance are usually much shorter in code than are implementations constructed with composition

• Composition: Simpler than inheritance.

• It more clearly indicates exactly what operations can be performed on a particular data structure.

135

• Looking at the Stack data abstraction with composition, it is clear that the only operations provided for the data type are the test for emptiness, push, top and pop.

• This is true regardless of what operations are defined for vectors.

Composition and inheritance contrasted: Semantics

• Inheritance: It does not prevent the users from manipulating the new structure using methods from the parent class even if these are not appropriate.

136

pp p

• For example, nothing prevents a Stack user from adding new elements using insertElementAt() which would be semantically illegal for the Stack data structure.

Page 35: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

35

Composition and inheritance contrasted: Information hiding

• Inheritance: A component constructed using

inheritance has access to fields and methods in

the parent class that have been declared as

137

p

public or protected.

• Composition: A component constructed using composition can only access the public portions of the included component.

– In the example, the fact that the class Vector is used is an implementation detail

138

is an implementation detail.

– It would be easy to re-implement the class to make use of a different technique (such as a linked list) with minimal impact on the users of the Stack abstraction.

– If users counted on the fact that a Stack is merely a specialized form of Vector, such changes would be more difficult to implement.

Determining visibility

• Visibility: the ability of an object to “see” or have reference to another object.

• For a sender object to send a message to a receiver object the receiver must be visible to the sender the

139

object, the receiver must be visible to the sender – the sender must have some kind of reference (or pointer) to the receiver object.

Visibility between objects

• The getSpecification()message sent from a Register to a ProductCatalog,

:Register

addLineItem(itemID, quantity)

140

g,implies that the ProductCataloginstance is visible to the Register instance.

:ProductCatalog

1: spec := getSpecification(itemID)

Page 36: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

36

• The Register must have visibility to the ProductCatalog.

• A typical visibility solution:Register

addLineItem(itemID, quantity)

141

• A typical visibility solution is that a reference to the ProductCataloginstance is maintained as an attribute of the Register.

:ProductCatalog

1: spec := getSpecification(itemID)

Types of visibility

• How do we determine whether one resource (such as an instance) is within the scope of another?

• Visibility can be achieved from object A to object B in four common ways:

142

y– Attribute visibility: B is an attribute of A.– Parameter visibility: B is a parameter of a method of A.

– Local visibility: B is a (non-parameter) local object in a method of A.

– Global visibility: B is in some way globally visible.

Attribute visibility

• Attribute visibility from A to B exists when B is an attribute of A.

• It is a relatively permanent visibility, because it persists as long as A and B exist

143

as long as A and B exist.

• In the example, if Register needs to send message getSpecification() to a ProductCatalog, then visibility from Register to ProductCatalog is required.

class Register {…private ProductCatalog catalog;…

public void addLineItem (…) { … }}

:Register

addLineItem(itemID, quantity)

144

}

public void addLineItem (ID itemID,int quantity) {

…spec = catalog.getSpecification(itemID);…

}:ProductCatalog

1: spec := getSpecification(itemID)

Page 37: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

37

Parameter visibility

• Parameter visibility from A to B exists when B is passed as a parameter to a method of A.

• It is a relatively temporary visibility, because it persists only within the scope of the method

145

only within the scope of the method.

:Register

addLineItem(itemID,quantity)

:Sale

2: makeLineItem(spec, quantity)

makeLineItem(ProductSpecification spec, int quantity) {…sli = new SalesLineItem(spec, quantity);…

}

146

: ProductCatalog

1: spec := getSpecification(itemID)

sli: SalesLineItem

3: create(spec, quantity)

• When message makeLineItem() is sent to a Saleinstance, a ProductSpecification instance is passed as a parameter.

Transforming parameter visibility to attribute visibility

• When Sale creates a new SalesLineItem, it passes a ProductSpecification to its constructor.

// constructorSalesLineItem(ProductSpecification spec,

int quantity) {

147

int quantity) { ...// parameter to attribute visibilityproductSpec = spec;...}

• We can assign ProductSpecification to an attribute in the constructor, thus transforming parameter visibility to attribute visibility.

Local visibility

• Locally declared visibility from A to B exists when B is declared as a local object within a method of A.

• It is relatively temporary visibility because it persists only within the scope of the method. Can be achieved as follows:

148

1. Create a new local instance and assign it to a local variable.2. Assign the return object from a method invocation to a local

variable.

addLineItem(itemID, quantity) {...ProductSpecification spec =

catalog.getSpecification(itemID);...}

Page 38: Part V: Object-Oriented Programming with Javausers.encs.concordia.ca/~bentahar/COMP348/Part 5 (Summer...1 Part V: Object-Oriented Programming with Java COMP 348/1: Principles ofCOMP

38

Global visibility

• Global visibility from A to B exists when B is global to A.

• It is a relatively permanent visibility because it persists as long as A and B exist.

149

• One way to achieve this is to assign an instance to a global variable.

Object features

• We distinguish between mutator methods, which

change an object, and accessor methods, which

merely read its data fields.

150

• The features of an object refer to the

combination of the state and the behavior of the

object.

Bibliography

• Timothy Budd, Understanding Object-Oriented Programming with Java (Updated Edition), Addison-Wesley, 2000.

• Xiaoping Jia, Object-Oriented Software Development Using Java Addison-Wesley 2000

151

Using Java, Addison Wesley, 2000.

• Robert W. Sebesta, Concepts of Programming Languages (7th edition), Addison Wesley, 2005.

• Alan Snyder, The Essence of Objects: Common Concepts and Terminology, Hewlett Packard Technical Report HPL-91-50, June 12, 1991. Also in IEEE Software, January 1993.