inheritance, polymorphism, and interfacesdszajda/classes/iqs2/spring_2013/lectures/... ·...

75
INHERITANCE, POLYMORPHISM, AND INTERFACES CODE EXAMPLES FROM JAVA: AN INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING (6 TH EDITION), BY WALTER SAVITCH IQS2: Spring 2013

Upload: others

Post on 10-Mar-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

INHERITANCE POLYMORPHISM AND INTERFACES

CODE EXAMPLES FROM JAVA AN INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING (6TH EDITION) BY

WALTER SAVITCH

IQS2 Spring 2013

Objectives

uml Describe polymorphism and inheritance in general

uml Define interfaces to specify methodsuml Describe dynamic bindinguml Define and use derived classes in Javauml Understand how inheritance is used in the JFrame class

2

Inheritance Basics Outline

uml Derived Classesuml Overriding Method Definitionsuml Overriding Versus Overloadinguml The final Modifieruml Private Instance Variables and Private Methods

of a Base Classuml UML Inheritance Diagrams

3

Inheritance Basics

uml Inheritance allows programmer to define a general class

uml Later you define a more specific classcurren Adds new details to general definition

uml New class inherits all properties of initial general class

uml Example the Person class

4

5

Derived Classes

uml An example class hierarchy6

Derived Classes

uml Person class used as a base classcurren Also called superclass

uml Student is a derived classcurren Also called subclasscurren Inherits methods and members from the superclass

7

8

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 2: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Objectives

uml Describe polymorphism and inheritance in general

uml Define interfaces to specify methodsuml Describe dynamic bindinguml Define and use derived classes in Javauml Understand how inheritance is used in the JFrame class

2

Inheritance Basics Outline

uml Derived Classesuml Overriding Method Definitionsuml Overriding Versus Overloadinguml The final Modifieruml Private Instance Variables and Private Methods

of a Base Classuml UML Inheritance Diagrams

3

Inheritance Basics

uml Inheritance allows programmer to define a general class

uml Later you define a more specific classcurren Adds new details to general definition

uml New class inherits all properties of initial general class

uml Example the Person class

4

5

Derived Classes

uml An example class hierarchy6

Derived Classes

uml Person class used as a base classcurren Also called superclass

uml Student is a derived classcurren Also called subclasscurren Inherits methods and members from the superclass

7

8

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 3: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Inheritance Basics Outline

uml Derived Classesuml Overriding Method Definitionsuml Overriding Versus Overloadinguml The final Modifieruml Private Instance Variables and Private Methods

of a Base Classuml UML Inheritance Diagrams

3

Inheritance Basics

uml Inheritance allows programmer to define a general class

uml Later you define a more specific classcurren Adds new details to general definition

uml New class inherits all properties of initial general class

uml Example the Person class

4

5

Derived Classes

uml An example class hierarchy6

Derived Classes

uml Person class used as a base classcurren Also called superclass

uml Student is a derived classcurren Also called subclasscurren Inherits methods and members from the superclass

7

8

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 4: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Inheritance Basics

uml Inheritance allows programmer to define a general class

uml Later you define a more specific classcurren Adds new details to general definition

uml New class inherits all properties of initial general class

uml Example the Person class

4

5

Derived Classes

uml An example class hierarchy6

Derived Classes

uml Person class used as a base classcurren Also called superclass

uml Student is a derived classcurren Also called subclasscurren Inherits methods and members from the superclass

7

8

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 5: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

5

Derived Classes

uml An example class hierarchy6

Derived Classes

uml Person class used as a base classcurren Also called superclass

uml Student is a derived classcurren Also called subclasscurren Inherits methods and members from the superclass

7

8

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 6: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Derived Classes

uml An example class hierarchy6

Derived Classes

uml Person class used as a base classcurren Also called superclass

uml Student is a derived classcurren Also called subclasscurren Inherits methods and members from the superclass

7

8

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 7: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Derived Classes

uml Person class used as a base classcurren Also called superclass

uml Student is a derived classcurren Also called subclasscurren Inherits methods and members from the superclass

7

8

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 8: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

8

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 9: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

9

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 10: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

10

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 11: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Donrsquot Recode What Is Already Coded

uml When you implement a subclass you getcurren All of the data members of the base classhellip

n hellipthough you may not be able to access them the way yoursquod like More on that later

curren All of the methods of the base classhellipn hellipwith same caveat as above

uml So donrsquot add or recode them in the subclassuml BUT it may be that you donrsquot like the way some methods

are codedused in the base class In that casehellip

11

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 12: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Overriding Method Definitions

uml Note method writeOutput in class Studentcurren Class Person also has method with that name

uml Method in subclass with same signature overrides method from base classcurren When an instance of the Student class calls the writeOutput() method the version of the method that is run is the one shown in the Student class

uml Overriding method must return same type of value

12

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 13: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Overriding Versus Overloading

uml Do not confuse overriding with overloadingcurren Overriding takes place in subclass ndash new method

with same signatureuml Overloading

curren New method in same class with different signaturen Example In String class

13

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 14: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The final Modifier

uml Possible to specify that a method cannot be overridden in subclass

uml Add modifier final to the headingpublic final void specialMethod()

uml An entire class may be declared finalcurren Thus cannot be used as a base class to derive any

other classuml Included here for completeness Irsquove never

used the final modifier for an entire class

14

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 15: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Private Instance Variables Methods

uml private instance variable in a base classcurren Are inherited in subclass (despite what your text

may say) but canrsquot be directly manipulated by you)curren Can only be manipulated by public accessor

modifier methodsuml Similarly private methods in a superclass

cannot be called in your subclass codecurren Which at times is not pleasant But itrsquos almost

always OK Why

15

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 16: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Protected Instance Variables Methods

uml protected instance variables and methods in a base classcurren Can be used any way you want in any descendent

class of the base classcurren Can be used any way you want inside any method

in any class in the same packagen See Appendix 5 in your text

16

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 17: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Constructors in Derived Classes

uml A derived class does not inherit constructors from base classcurren Constructor in a subclass must invoke constructor

from base classuml Use the reserve word super

curren Must be first action in the constructor

17

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 18: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The this Method ndash Again

uml Also possible to use the this keywordsect Use to call any constructor in the class

uml When used in a constructor this calls constructor in same classsect Contrast use of super which invokes constructor of

base classsect Again here for completeness

18

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 19: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Calling an Overridden Method

uml Reserved word super can also be used to call method in overridden method

uml Calls method by same name in base class

19

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 20: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Programming Example

uml A derived class of a derived class Undergraduate class

uml Has all public members of bothsect Personsect Student

uml This reuses the code in superclasses

20

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 21: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

21

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 22: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

22

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 23: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Type Compatibility

uml In the class hierarchycurren Each Undergraduate is also a Studentcurren Each Student is also a Person

uml An object of a derived class can serve as an object of the base class (that is used wherever the base class is required)curren Ex as input parameters to methodscurren Note this is not typecasting

uml An object of a class can be referenced by a variable of an ancestor typecurren So for example a Person variable can point to (reference)

an Undergraduate object (but not vice versa)

23

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 24: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Type Compatibility

uml Be aware of the is-a relationshipcurren An Undergraduate is a PersoncurrenBut a Person is not necessarily an Undergraduate

uml Another relationship is the has-acurren A class can contain (as an instance variable) an

object of another typecurren If we specify a date of birth variable for Person

ndash it has-a Date object

24

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 25: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The Class Object

uml Java has a class that is the ultimate ancestor of every classsect The class Object

uml Thus possible to write a method with parameter of type Objectsect Actual parameter in the call can be object of any type

uml Example method println(Object theObject)

25

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 26: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The Class Object

uml Class Object has some methods that every Java class inherits

uml Examplessect Method equalssect Method toString

uml Method toString called when println(theObject) invokedsect Best to define your own toString to handle this

26

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 27: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

A Better equals Method

uml Programmer of a class should override method equals from Object

uml View code of a better equals methodpublic boolean equals (Object theObject)

27

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 28: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

28

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 29: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Polymorphismuml Inheritance allows you to define a base class

and derive classes from the base classuml Polymorphism allows you to make changes in

the method definition for the derived classes and have those changes apply to methods written in the base class

29

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 30: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Polymorphismuml Consider an array of PersonPerson[] people = new Person[4]

uml Since Student and Undergraduate are types of Person we can assign them to Person variables

people[0] = new Student(DeBanque Robin 8812)

people[1] = new Undergraduate(Cotty Manny 8812 1)

30

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 31: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Polymorphismuml GivenPerson[] people = new Person[4]people[0] = new Student(DeBanque Robin 8812)

uml When invokingpeople[0]writeOutput()

uml Which writeOutput() is invoked the one defined for Student or the one defined for Person

uml Answer The one defined for Student

31

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 32: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

An Inheritance as a Type

uml The method can substitute one object for anothercurren Called polymorphism

uml This is made possible by mechanism curren Dynamic bindingcurren Also known as late binding

32

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 33: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Dynamic Binding and Inheritance

uml When an overridden method invokedsect Action matches method defined in class used to create

object using newsect Not determined by type of variable naming the object

uml Variable of any ancestor class can reference object of descendant classsect Object always remembers which method actions to use

for each method name

33

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 34: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Polymorphism Example

uml View sample class listing 86class PolymorphismDemo

uml Output

34

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 35: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

35

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 36: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

36

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 37: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

An Aside Types and Security37

uml Java is a ldquostrongly typedrdquo languagecurren This means that it is very careful about making sure

appropriate typed objects are passed to methods and assigned as references

uml All other factors being equal strong typing makes a language much more secure curren Can anyone guess why this is

uml But it turns out that the Java type system can be fooled via careful (mis)use of the dynamic binding system

n And if you manage to fool it even once you have rendered the type system completely ineffective

n The method researchers discovered for doing this is considered so dangerous that it has never been published

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 38: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Class Interfaces

uml Consider a set of behaviors for petscurren Be namedcurren Eatcurren Respond to a command

uml We could specify method headings for these behaviors

uml These method headings can form a class interface

38

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 39: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Class Interfaces

uml Now consider different classes that implement this interfacecurren They will each have the same behaviorscurren Nature of the behaviors will be different

uml Each of the classes implements the behaviorsmethods differently

39

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 40: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Java Interfaces

uml A program component that contains headings for a number of public methodscurren Will include comments that describe the methods

uml Interface can also define public named constants

40

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 41: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

41

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 42: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Java Interfaces

uml Interface name begins with uppercase letteruml Stored in a file with suffix javauml Interface does not include

curren Declarations of constructorscurren Instance variablescurren Method bodies

42

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 43: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Implementing an Interface

uml To implement a method a class mustsect Include the phrase

implements Interface_namesect Define each specified method

43

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 44: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

44

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 45: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

45

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 46: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

An Inheritance as a Type

uml Possible to write a method that has an Interface type as a parametercurren An interface is a reference type

uml Program invokes the method passing it an object of any class which implements that interface

46

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 47: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Example Genetic Algorithm47

uml A Population described by chromosomesuml Crossoveruml Mutationuml Survival of the fittest

curren Fitness function

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 48: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Flow Diagram of the Genetic Algorithm Process

Describe Problem

Generate InitialSolutions

Test is initialsolution good enough

Stop

Select parents to reproduce

Apply crossover process and create a set of offspring

Apply random mutation

Step 1

Step 2

Step 3

Step 4

Step 5

Yes

No

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 49: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

49

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 50: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The Comparator Interface50

uml Required for use in Java Arrays classcurren Arrayssort()

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 51: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Extending an Interface

uml Possible to define a new interface which builds on an existing interfacecurren It is said to extend the existing interface

uml A class that implements the new interface must implement all the methods of both interfaces

51

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 52: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

(Another) Case Study

uml Java has many predefined interfacesuml One of them the Comparable interface is used to

impose an ordering upon the objects that implement it

uml Requires that the method compareTo be written public int compareTo(Object other)

52

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 53: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Sorting an Array of Fruit Objects

uml Initial (non-working) attempt to sort an array of Fruit objects

uml View class definition listing 816class Fruit

uml View test class listing 817class FruitDemo

uml Result Exception in thread ldquomainrdquocurren Sort tries to invoke compareTo method but it

doesnrsquot exist

53

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 54: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Sorting an Array of Fruit Objects

uml Working attempt to sort an array of Fruit objects ndash implement Comparable write compareTo method

uml Following slides show Fruit classuml Result Exception in thread ldquomainrdquo

curren Sort tries to invoke method but it doesnrsquot exist

54

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 55: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

compareTo Method

uml An alternate definition that will sort by length of the fruit name

59

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 56: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Abstract Classes

uml Class ShapeBasics is designed to be a base class for other classescurren Method drawHere will be redefined for each

subclasscurren It should be declared abstract ndash a method that has

no bodyuml This makes the class abstractuml You cannot create an object of an abstract

class ndash thus its role as base class

60

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 57: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Abstract Classes

uml Not all methods of an abstract class are abstract methods

uml Abstract class makes it easier to define a base classcurren Specifies the obligation of designer to override the

abstract methods for each subclass

61

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 58: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Abstract Classes

uml Cannot have an instance of an abstract classcurren But OK to have a parameter of that type

62

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 59: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Dynamic Binding and Inheritanceuml How does Java know which version of a method is to

be runuml Happens with dynamic or late binding

sect Address of correct code to be executed determined at run time

63

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 60: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Graphics Supplement Outline

uml The Class JAppletuml The Class JFrameuml Window Events and Window Listenersuml The ActionListener Interface

64

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 61: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The Class JApplet

uml Class JApplet is base class for all appletssect Has methods init and paint

uml When you extend JApplet you override (redefine) these methods

uml Parameter shownwill use your versions due topolymorphism

65

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 62: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The Class JFrame

uml For GUIs to run as applications (instead of from a web page)sect Use class JFrame as the base class

uml View example program listing 820class ButtonDemo

uml Note method setSizesect Width and height given in number of pixelssect Sets size of window

66

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 63: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The Class JFrame

uml View demo program listing 821class ShowButtonDemo

Sample screen output

67

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 64: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Window Events and Window Listeners

uml Close-window button fires an event curren Generates a window event handled by a window

listeneruml View class for window events

listing 822 class WindowDestroyeruml Be careful not to confuse JButtons and the

close-window button

68

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 65: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

The ActionListener Interface

uml Use of interface ActionListener requires only one method public void actionPerformed (ActionEvent e)

uml Listener that responds to button clickssect Must be an action listenersect Thus must implement ActionListener interface

69

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 66: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Summary

uml An interface contains curren Headings of public methodscurren Definitions of named constantscurren No constructors no private instance variables

uml Class which implements an interface mustcurren Define a body for every interface method specified

uml Interface enables designer to specify methods for another programmer

70

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 67: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Summary

uml Interface is a reference typecurren Can be used as variable or parameter type

uml Interface can be extended to create another interface

uml Dynamic (late) binding enables objects of different classes to substitute for one anothercurren Must have identical interfacescurren Called polymorphism

71

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 68: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Summary

uml Derived class obtained from base class by adding instance variables and methodscurren Derived class inherits all public elements of base

classuml Constructor of derived class must first call a

constructor of base classcurren If not explicitly called Java automatically calls

default constructor

72

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 69: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Summary

uml Within constructorsect this calls constructor of same class

sect super invokes constructor of base class

uml Method from base class can be overriddensect Must have same signature

uml If signature is different method is overloaded

73

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 70: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Summary

uml Overridden method can be called with preface of super

uml Private elements of base class cannot be accessed directly by name in derived class

uml Object of derived class has type of both base and derived classes

uml Legal to assign object of derived class to variable of any ancestor type

74

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75

Page 71: INHERITANCE, POLYMORPHISM, AND INTERFACESdszajda/classes/IQS2/Spring_2013/lectures/... · inheritance, polymorphism, and interfaces code examples from java: an introduction to programming

Summary

uml Every class is descendant of class Objectuml Class derived from JFrame produces applet

like window in application programuml Method setSize resizes JFrame windowuml Class derived from WindowAdapter defined

to be able to respond to closeWindow button

75