inheritance and polymorphism

68
Inheritance and Polymorphism Inheritance and Polymorphism Object-Oriented Object-Oriented Programming in Programming in Java Java

Upload: bg-java-ee-course

Post on 01-Nov-2014

19 views

Category:

Technology


0 download

DESCRIPTION

OOP principles

TRANSCRIPT

Page 1: Inheritance and Polymorphism

Inheritance and PolymorphismInheritance and Polymorphism

Object-Oriented Object-Oriented Programming in Programming in

JavaJava

Page 2: Inheritance and Polymorphism

ContentsContents

1.1. Inheritance in JavaInheritance in Java

• Inheriting ClassesInheriting Classes

• The The supersuper Reference Reference

• Overriding MethodsOverriding Methods

• PolymorphismPolymorphism

• The The instanceofinstanceof Operator Operator

• final Methods and Classesfinal Methods and Classes

2

Page 3: Inheritance and Polymorphism

Contents (2)Contents (2)

1.1. Abstract ClassesAbstract Classes

• Abstract MethodsAbstract Methods

2.2. InterfacesInterfaces

• Defining InterfacesDefining Interfaces

• Implementing InterfacesImplementing Interfaces

3.3. Using Interfaces (Demo)Using Interfaces (Demo)

3

Page 4: Inheritance and Polymorphism

Access ModifiersAccess Modifierspublic, private, protected, default public, private, protected, default

(package)(package)

Page 5: Inheritance and Polymorphism

Access ModifiersAccess Modifiers

• The most common modifiers are the access The most common modifiers are the access modifiers:modifiers:

• publicpublic

• privateprivate

• protectedprotected

• (default)(default)

• Access modifiers control which classes Access modifiers control which classes may use a membermay use a member

5

Page 6: Inheritance and Polymorphism

Access Modifiers RulesAccess Modifiers Rules

• The variables that you declare and use The variables that you declare and use within a class’s methods may not have within a class’s methods may not have access modifiersaccess modifiers

• The only access modifier permitted to non-The only access modifier permitted to non-inner classes is inner classes is publicpublic

• A member may have at most one access A member may have at most one access modifiermodifier

6

Page 7: Inheritance and Polymorphism

publicpublic

• The most generous access modifier is The most generous access modifier is publicpublic

• A A publicpublic class, variable, or method may be class, variable, or method may be used in any Java program without used in any Java program without restrictionrestriction

• Any Any publicpublic method may be overridden by method may be overridden by any subclassany subclass

7

Page 8: Inheritance and Polymorphism

privateprivate

• The least generous access modifier is The least generous access modifier is privateprivate

• Top-level (that is, not inner) classes may Top-level (that is, not inner) classes may not be declared not be declared privateprivate

• A A privateprivate variable or method may be used variable or method may be used only by an instance of the class that only by an instance of the class that declares the variable or methoddeclares the variable or method

8

Page 9: Inheritance and Polymorphism

protectedprotected

• Only variables and methods may be Only variables and methods may be declared declared protectedprotected

• A A protectedprotected member of a class is member of a class is available to all classes in the same available to all classes in the same package, just like a default memberpackage, just like a default member

• A A protectedprotected member of a class can be member of a class can be available in certain limited ways to all available in certain limited ways to all subclasses of the class that owns the subclasses of the class that owns the protectedprotected member. It is visible in member. It is visible in subclasses in different packages too.subclasses in different packages too.9

Page 10: Inheritance and Polymorphism

(default)(default)

• DefaultDefault is the name of the access of is the name of the access of classes, variables, and methods if you classes, variables, and methods if you don’tdon’t specify an access modifierspecify an access modifier

• A class’s data and methods may be default, A class’s data and methods may be default, as well as the class itselfas well as the class itself

• A class’s default members are accessible to A class’s default members are accessible to any class in the same package as the class any class in the same package as the class in questionin question

• A default method may be overridden by any A default method may be overridden by any subclass that is in the same package as the subclass that is in the same package as the superclasssuperclass 10

Page 11: Inheritance and Polymorphism

Applying Encapsulation in Applying Encapsulation in JavaJava

• Instance variables should be Instance variables should be declared as declared as privateprivate

• Only instance methods can Only instance methods can access access privateprivate instance instance variablesvariables

Movie mov1 = new Movie();Movie mov1 = new Movie();String rating = mov1.getRating();String rating = mov1.getRating();String r = mov1.rating; // Error: privateString r = mov1.rating; // Error: private ......if (rating.equals("G"))if (rating.equals("G"))

var

aMethod

aMethod()

Page 12: Inheritance and Polymorphism

PackagesPackages

Page 13: Inheritance and Polymorphism

What Are Java Packages?What Are Java Packages?

• A package is a container of classes that are logically related

• A package consists of all the Java classes within a directory on the file system

• Package names and used within a JRE to manage the uniqueness of identifiers

• They segment related parts of complex applications into manageable parts

Page 14: Inheritance and Polymorphism

Grouping Classes in a Grouping Classes in a PackagePackage

• Include the Include the packagepackage keyword followed by keyword followed by one or more names separated by dots at the one or more names separated by dots at the top of the Java source filetop of the Java source file

• If omitted the compiler places the class in If omitted the compiler places the class in the default “unnamed” packagethe default “unnamed” package 14

package utils;package utils;

public class MathUtils {public class MathUtils { ......}}

Page 15: Inheritance and Polymorphism

Grouping Classes in a Grouping Classes in a PackagePackage

• To run a To run a main()main() method in a packaged method in a packaged class requires:class requires:

• The CLASSPATH to contain the directory The CLASSPATH to contain the directory having the root name of the package treehaving the root name of the package tree

• The class name must be qualified by itsThe class name must be qualified by itspackage namepackage name

15

java –cp . myPackage.MainClassjava –cp . myPackage.MainClass

Page 16: Inheritance and Polymorphism

The CLASSPATH with The CLASSPATH with PackagesPackages

• Includes the directory containing the top level Includes the directory containing the top level of the package treeof the package tree

16C:\>set CLASSPATH=E:\Curriculum\courses\java\C:\>set CLASSPATH=E:\Curriculum\courses\java\practices\les06practices\les06

Package name .class location

CLASSPATH

Page 17: Inheritance and Polymorphism

Importing PackagesImporting Packages

• To use a class defined in other package To use a class defined in other package (not in current) you should do either:(not in current) you should do either:

• Import the class or all classes in the Import the class or all classes in the package:package:

• Use the full name of the class:Use the full name of the class:

17

import utils.MathUtils;import utils.MathUtils;......int sq = MathUtils.FastCalculateSqrt(12345);int sq = MathUtils.FastCalculateSqrt(12345);

int sq = utils.MathUtils.FastCalculateSqrt(12345);int sq = utils.MathUtils.FastCalculateSqrt(12345);

Page 18: Inheritance and Polymorphism

Inheritance and Inheritance and PolymorphismPolymorphismCode Reuse TechniquesCode Reuse Techniques

Page 19: Inheritance and Polymorphism

Key Object-Oriented Key Object-Oriented ComponentsComponents

InheritanceInheritance

Constructors referenced by subclassConstructors referenced by subclass

PolymorphismPolymorphism

Inheritance is an OO fundamentalInheritance is an OO fundamental

InventoryItemInventoryItem

MovieMovie GameGame BookBook

Superclass

Subclasses

Page 20: Inheritance and Polymorphism

Example of Inheritance Example of Inheritance

The The InventoryItemInventoryItem class defines methods class defines methods and variablesand variables

Movie extends Movie extends InventoryItemInventoryItem and can: and can:

Add new variables Add new variables

Add new methodsAdd new methods

Override methods in Override methods in InventoryItemInventoryItem class class

InventoryItemInventoryItem

MovieMovie

Page 21: Inheritance and Polymorphism

Specifying Inheritance in Specifying Inheritance in JavaJava

Inheritance is achieved by specifying which Inheritance is achieved by specifying which superclass the subclass extendssuperclass the subclass extends

Movie inherits all the variables and methods Movie inherits all the variables and methods of of InventoryItemInventoryItem

public class InventoryItem {public class InventoryItem { … … }}

public class Movie public class Movie extendsextends InventoryItem { InventoryItem { … … }}

Page 22: Inheritance and Polymorphism

What Does a Subclass What Does a Subclass Object Look Like?Object Look Like?

A subclass inherits all the instance A subclass inherits all the instance variables of its superclassvariables of its superclass

Movie

titletitlelengthlength

pricepriceconditioncondition

public classpublic class Movie extends InventoryItem {Movie extends InventoryItem { private String title;private String title; private int length; … private int length; … }}

public class InventoryItem {public class InventoryItem { private float price;private float price; private String condition; … private String condition; … }}

Page 23: Inheritance and Polymorphism

Default InitializationDefault Initialization

What happens when a What happens when a subclass object is created?subclass object is created?

If no constructors are defined: If no constructors are defined:

First, the default First, the default parameterless constructor is parameterless constructor is called in the superclasscalled in the superclass

Then, the default Then, the default parameterless constructor is parameterless constructor is called in the subclasscalled in the subclass

Movie movie1 = new Movie();Movie movie1 = new Movie();

Movie

titletitlelengthlength

pricepriceconditioncondition

Page 24: Inheritance and Polymorphism

The The supersuper Reference Reference

Refers to the base classRefers to the base class

Is useful for calling base class Is useful for calling base class constructorsconstructors Must be the first line in the derived class Must be the first line in the derived class

constructorconstructor

Can be used to call any base class Can be used to call any base class methodsmethodspublic class Movie extends InventoryItem {public class Movie extends InventoryItem { public Movie() {public Movie() { super("Matrix 8");super("Matrix 8"); } } }}

Page 25: Inheritance and Polymorphism

The The supersuper Reference Reference ExampleExample

public class InventoryItem {public class InventoryItem { InventoryItem(String cond) {InventoryItem(String cond) { System.out.println("InventoryItem");System.out.println("InventoryItem"); … … }}}}class Movie extends InventoryItem {class Movie extends InventoryItem { Movie(String title) {Movie(String title) { super(title);super(title); … … System.out.println("Movie");System.out.println("Movie"); }}}}

Base class Base class constructorconstructor

Calls baseCalls baseclassclass

constructorconstructor

Page 26: Inheritance and Polymorphism

Using Superclass Using Superclass ConstructorsConstructors

• Use Use super()super() to call a superclass to call a superclass constructor:constructor:

public class InventoryItem {public class InventoryItem { InventoryItem(float p, String cond) {InventoryItem(float p, String cond) { price = p;price = p; condition = cond;condition = cond; } … } …

public class Movie extends InventoryItem public class Movie extends InventoryItem {{ Movie(String t, float p, String cond) {Movie(String t, float p, String cond) { super(p, cond); super(p, cond); title = t;title = t; } … } …

Page 27: Inheritance and Polymorphism

Specifying Additional Specifying Additional MethodsMethods

The superclass defines methods for all The superclass defines methods for all types of types of InventoryItemInventoryItem

The subclass can specify additional The subclass can specify additional methods that are specific to methods that are specific to MovieMovie

public class InventoryItem {public class InventoryItem { public float calcDeposit()… public float calcDeposit()… public String calcDateDue()…public String calcDateDue()… … …

public class Movie extends InventoryItem {public class Movie extends InventoryItem { public void getTitle()… public void getTitle()… public String getLength()… public String getLength()…

Page 28: Inheritance and Polymorphism

Overriding Superclass Overriding Superclass MethodsMethods

A subclass inherits all the methods of its A subclass inherits all the methods of its superclasssuperclass

The subclass can override a method with its The subclass can override a method with its own specialized versionown specialized version

Must have the same signature and semantics Must have the same signature and semantics as the superclass methodas the superclass method

In Java all methods are virtual (unless In Java all methods are virtual (unless declared as declared as finalfinal)) This forces the This forces the late bindinglate binding mechanism on mechanism on

each method calleach method call

Page 29: Inheritance and Polymorphism

Overriding Superclass Overriding Superclass Methods – ExampleMethods – Example

public class InventoryItem {public class InventoryItem { … … public float calcDeposit(int custId) {public float calcDeposit(int custId) { return itemDeposit;return itemDeposit; }}}}

public class Movie extends InventoryItem {public class Movie extends InventoryItem { … … public float calcDeposit(int custId) {public float calcDeposit(int custId) { if (specialCustomer(custId) { if (specialCustomer(custId) { return itemDeposit / 2;return itemDeposit / 2; } else {} else { return itemDeposit;return itemDeposit; } } }}}}

Page 30: Inheritance and Polymorphism

Invoking Superclass Invoking Superclass MethodsMethods

If a subclass overrides a method, it can still If a subclass overrides a method, it can still call the original superclass methodcall the original superclass method

Use Use super.method()super.method() to call a superclass to call a superclass method from the subclassmethod from the subclasspublic class InventoryItem {public class InventoryItem { public float calcDeposit(int custId) {public float calcDeposit(int custId) { if … if … return 33.00;return 33.00; }}

public class Movie extends InventoryItem {public class Movie extends InventoryItem { public float calcDeposit(int custId) {public float calcDeposit(int custId) { itemDeposit = super.calcDeposit(custId); itemDeposit = super.calcDeposit(custId); return (itemDeposit + vcrDeposit); return (itemDeposit + vcrDeposit); }}

Page 31: Inheritance and Polymorphism

Treating a Subclass as Its Treating a Subclass as Its SuperclassSuperclass

A Java object instance of a subclass is plug A Java object instance of a subclass is plug compatible with its superclass definitioncompatible with its superclass definition You can assign a subclass object to a You can assign a subclass object to a

reference declared with the superclass:reference declared with the superclass:

The compiler treats the object via its The compiler treats the object via its reference, that is, in terms of its superclass reference, that is, in terms of its superclass definitiondefinition

The JVM creates a subclass object, executing The JVM creates a subclass object, executing subclass methods, if overriddensubclass methods, if overridden

31

public static void main(String[] args) {public static void main(String[] args) { InventoryItem item = new Movie();InventoryItem item = new Movie(); double deposit = item.calcDeposit();double deposit = item.calcDeposit();}}

Page 32: Inheritance and Polymorphism

Acme Video and Acme Video and PolymorphismPolymorphism

Acme Video started renting only videosAcme Video started renting only videos

Acme Video added games and VCRsAcme Video added games and VCRs

What’s next?What’s next?

Polymorphism solves the problemPolymorphism solves the problem

Page 33: Inheritance and Polymorphism

ShoppingBasketShoppingBasketvoid addItem(InventoryItem item) {void addItem(InventoryItem item) { // this method is called each time// this method is called each time // the clerk scans in a new item// the clerk scans in a new item float deposit = item.calcDeposit();float deposit = item.calcDeposit(); … …}}

InventoryItemInventoryItem

VCRVCR MovieMovie

calcDeposit(){…}calcDeposit(){…}

calcDeposit(){…}calcDeposit(){…}calcDeposit(){…}calcDeposit(){…}

How It WorksHow It Works

Page 34: Inheritance and Polymorphism

Using the Using the instanceofinstanceof OperatorOperator

The true type of an object can be The true type of an object can be determined by using an determined by using an instanceofinstanceof operatoroperator

An object reference can be downcast to the An object reference can be downcast to the correct type, if neededcorrect type, if needed

public void aMethod(InventoryItem i) {public void aMethod(InventoryItem i) { … … if (i instanceof Movie)if (i instanceof Movie) ((Movie)i).playTestTape();((Movie)i).playTestTape();}}

Page 35: Inheritance and Polymorphism

Limiting Methods and Limiting Methods and Classes with Classes with finalfinal

A method can be marked as A method can be marked as finalfinal to prevent to prevent it from being overriddenit from being overridden

A whole class can be marked as A whole class can be marked as finalfinal to to prevent it from being extendedprevent it from being extended

public final class Color {public final class Color { … … }}

public final boolean checkPassword(String p) {public final boolean checkPassword(String p) { … … }}

Page 36: Inheritance and Polymorphism

When to Use Inheritance?When to Use Inheritance?

Inheritance should be used only for “is a Inheritance should be used only for “is a kind of” relationships:kind of” relationships: It must always be possible to substitute a It must always be possible to substitute a

subclass object for a superclass objectsubclass object for a superclass object

All methods in the superclass should make All methods in the superclass should make sense in the subclasssense in the subclass

Inheritance for short-term convenience Inheritance for short-term convenience leads to problems in the futureleads to problems in the future

Page 37: Inheritance and Polymorphism

Abstract Classes and Abstract Classes and InterfacesInterfaces

Page 38: Inheritance and Polymorphism

Defining Abstract ClassesDefining Abstract Classes

Abstract classes model abstract Abstract classes model abstract concepts from the real worldconcepts from the real world Cannot be instantiated directlyCannot be instantiated directly Should be subclasses to be instantiatedShould be subclasses to be instantiated

Abstract methods must be implemented Abstract methods must be implemented by subclassesby subclasses

Abstract superclass

Concrete subclasses

InventoryItemInventoryItem

MovieMovie VCRVCR

Page 39: Inheritance and Polymorphism

Creating Abstract ClassesCreating Abstract Classesin Javain Java

Use the Use the abstractabstract keyword to declare a keyword to declare a class as abstractclass as abstract

public public abstract classabstract class InventoryItem { InventoryItem { private float price;private float price; public boolean isRentable()… public boolean isRentable()… }}

public class Movie public class Movie extends InventoryItem {extends InventoryItem { private String title;private String title; public int getLength()…public int getLength()…

public class Vcr public class Vcr extends InventoryItem {extends InventoryItem { private int serialNbr;private int serialNbr; public void setTimer()…public void setTimer()…

Page 40: Inheritance and Polymorphism

What Are Abstract What Are Abstract Methods?Methods?

An abstract method:An abstract method: Is an implementation placeholderIs an implementation placeholder

Is part of an abstract classIs part of an abstract class

Must be overridden by a concrete subclassMust be overridden by a concrete subclass Each concrete subclass can implement the Each concrete subclass can implement the

method differentlymethod differently

Page 41: Inheritance and Polymorphism

Defining Abstract MethodsDefining Abstract Methodsin Javain Java

Use the abstract keyword to declare a method Use the abstract keyword to declare a method as as abstractabstract:: Provide the method signature onlyProvide the method signature only

The class must also be abstractThe class must also be abstract

Why is this useful?Why is this useful? Declare the structure of a class without Declare the structure of a class without

providing complete implementation of every providing complete implementation of every methodmethod

public abstract class InventoryItem {public abstract class InventoryItem { public public abstractabstract boolean isRentable(); boolean isRentable(); … …

Page 42: Inheritance and Polymorphism

Defining and Using Defining and Using InterfacesInterfaces

An interface is like a fully abstract class:An interface is like a fully abstract class: All of its methods are abstractAll of its methods are abstract

All variables are All variables are public static finalpublic static final

An interface lists a set of method signatures, An interface lists a set of method signatures, without any code detailswithout any code details

A class that implements the interface must A class that implements the interface must provide code details for all the methods of provide code details for all the methods of the interfacethe interface

A class can implement many interfaces but A class can implement many interfaces but can extend only one classcan extend only one class

Page 43: Inheritance and Polymorphism

Example of InterfacesExample of Interfaces

Interfaces describe an aspect of behavior Interfaces describe an aspect of behavior that different classes requirethat different classes require

For example, classes that can be steered For example, classes that can be steered support the “steerable” interfacesupport the “steerable” interface

Classes can be unrelatedClasses can be unrelated

SteerableNonsteerable

Page 44: Inheritance and Polymorphism

Creating an InterfaceCreating an Interface

Use Use interfaceinterface keyword keyword

All methods All methods public abstractpublic abstract All variables All variables public static finalpublic static final

public public interfaceinterface Steerable { Steerable { int MAXTURN_DEGREES = 45; int MAXTURN_DEGREES = 45; void turnLeft(int deg);void turnLeft(int deg); void turnRight(int deg);void turnRight(int deg);}}

Page 45: Inheritance and Polymorphism

Implementing an InterfaceImplementing an Interface

• Use Use implementsimplements keyword keyword

public class Yacht extends Boatpublic class Yacht extends Boatimplementsimplements Steerable Steerable

public void turnLeft(int deg) {…} public void turnLeft(int deg) {…} public void turnRight(int deg) {…}public void turnRight(int deg) {…}}}

Page 46: Inheritance and Polymorphism

Sort: A Real-World ExampleSort: A Real-World Example

Is used by a number of unrelated classesIs used by a number of unrelated classes Contains a known set of methodsContains a known set of methods Is needed to sort any type of objectsIs needed to sort any type of objects Uses comparison rules known only to the Uses comparison rules known only to the

sortable objectsortable object Supports good code reuseSupports good code reuse

Page 47: Inheritance and Polymorphism

Overview of the ClassesOverview of the Classes

Created by the sort expert:Created by the sort expert:

Created by the movie expert:Created by the movie expert:

public class public class MovieSortApplicationMovieSortApplication

public class Moviepublic class Movie implements Sortable implements Sortable

public interface public interface Sortable Sortable

public classpublic class SortSort

Page 48: Inheritance and Polymorphism

MyApplicationMyApplication passes passes an array of movies to an array of movies to Sort.sortObjects()Sort.sortObjects()

11

2233sortObjects()sortObjects() asks a asks a movie to compare itself movie to compare itself

with another moviewith another movie

The movie returns The movie returns the result of the the result of the

comparisoncomparison

44sortObjects()sortObjects()

returns the returns the sorted listsorted list

SortSort

MovieMovie

MyApplicationMyApplication

How the Sort Works?How the Sort Works?

Page 49: Inheritance and Polymorphism

The The SortableSortable InterfaceInterface

• Specifies the Specifies the compare()compare() method method

public interface Sortable {public interface Sortable { // compare(): Compare this object // compare(): Compare this object // to another object// to another object // Returns:// Returns: // 0 if this object is equal to obj2 // 0 if this object is equal to obj2 // a value < 0 if this object < obj2// a value < 0 if this object < obj2 // a value > 0 if this object > obj2// a value > 0 if this object > obj2 int compare(Object obj2);int compare(Object obj2);} }

Page 50: Inheritance and Polymorphism

The The SortSort Class Class

• Implements sorting functionality: the Implements sorting functionality: the method method sortObjects()sortObjects()

public class Sort { public class Sort { public static void sortObjects(Sortable[] items) {public static void sortObjects(Sortable[] items) { // Perform "Bubble sort" algorithm// Perform "Bubble sort" algorithm for (int i = 1; i < items.length; i++) {for (int i = 1; i < items.length; i++) { for (int j = 0; j < items.length-1; j++) {for (int j = 0; j < items.length-1; j++) { if (items[j].compare(items[j+1]) > 0) {if (items[j].compare(items[j+1]) > 0) { Sortable tempItem = items[j+1];Sortable tempItem = items[j+1]; items[j+1] = items[j];items[j+1] = items[j]; items[j] = tempItem;items[j] = tempItem; }} }} }} }}} }

Page 51: Inheritance and Polymorphism

public class Movie extends InventoryItempublic class Movie extends InventoryItem implements Sortableimplements Sortable { {

private String title;private String title; public int compare(Object movie2)public int compare(Object movie2) { { String title1 = this.title;String title1 = this.title; String title2 = ((Movie)movie2).getTitle();String title2 = ((Movie)movie2).getTitle(); return(title1.compareTo(title2));return(title1.compareTo(title2)); }}}}

• Implements Implements SortableSortable

The The MovieMovie Class Class

Page 52: Inheritance and Polymorphism

Using the SortUsing the Sort

• Call Call Sort.sortObjects(Sortable [])Sort.sortObjects(Sortable []) with an array of with an array of MovieMovie as the argument as the argument

public class MovieSortApplication {public class MovieSortApplication {

Movie[] movieList;Movie[] movieList;

public static void main(String[] args) {public static void main(String[] args) { … … // Build the array of Movie objects// Build the array of Movie objects … … Sort.sortObjects(movieList);Sort.sortObjects(movieList); }}}}

Page 53: Inheritance and Polymorphism

Sorting with InterfacesSorting with Interfaces

Live DemoLive Demo

Page 54: Inheritance and Polymorphism

Inner ClassesInner Classes

Page 55: Inheritance and Polymorphism

What Are Inner Classes?What Are Inner Classes?

• Inner classes are classes defined within a Inner classes are classes defined within a classclass

• Enforce a relationship between two classesEnforce a relationship between two classes

• Are of four types:Are of four types:

• Static Static

• MemberMember

• LocalLocal

• AnonymousAnonymous

public class Outer { … public class Outer { … class Inner { …class Inner { …

}}}}

Page 56: Inheritance and Polymorphism

Defining Static Inner Defining Static Inner ClassesClasses

• public class Outer {public class Outer {

• private static float varFloat = 3.50f;private static float varFloat = 3.50f;

• private String varString;private String varString;

• … …

• static class InnerStatic {static class InnerStatic {

• … …

• }}

• … …

• }}

• Defined at class levelDefined at class level

• Can access only static members of the outer Can access only static members of the outer classclass

Page 57: Inheritance and Polymorphism

Defining Member Inner Defining Member Inner ClassesClasses

• public class Outer {public class Outer {

• private static float varFloat = 3.50f;private static float varFloat = 3.50f;

• private String varString;private String varString; ... ... class InnerMember { class InnerMember { ... ... Outer.this Outer.this ... ... } }

• }}

• Defined at class levelDefined at class level

• Instance of the outer is neededInstance of the outer is needed

• Keyword Keyword thisthis used to access the outer instance used to access the outer instance

Page 58: Inheritance and Polymorphism

Defining Local Inner Defining Local Inner ClassesClasses

• Are defined at the method levelAre defined at the method level

• Are declared within a code blockAre declared within a code block

• Have access only to final variablesHave access only to final variables

• Cannot have a constructorCannot have a constructorpublic class Outer {public class Outer {...... public void outerMethod(final int var1){public void outerMethod(final int var1){ final int var2=5; ...final int var2=5; ...

class InnerLocal {class InnerLocal {private int localVar = var1 + var2; ...private int localVar = var1 + var2; ...

}} } }}}

Page 59: Inheritance and Polymorphism

Defining Anonymous Inner Defining Anonymous Inner ClassesClasses

• Defined at method levelDefined at method level

• Declared within a code blockDeclared within a code block

• Missing the Missing the classclass, , extendsextends, and , and implementsimplements keywords keywords

• Cannot have a constructorCannot have a constructor

public class Outer {public class Outer { public void outerMethod(){ public void outerMethod(){

myObject.myAnonymous(new SomeClass(){myObject.myAnonymous(new SomeClass(){ ... ... } )} ) } }}}

Page 60: Inheritance and Polymorphism

Using Using instanceofinstanceof with with InterfacesInterfaces

Use the Use the instanceofinstanceof operator to check if operator to check if an object implements an interfacean object implements an interface

Use downcasting to call methods defined Use downcasting to call methods defined in the interfacein the interface

public void aMethod(Object obj) {public void aMethod(Object obj) { … … if (obj if (obj instanceofinstanceof Sortable) { Sortable) { result = ((Sortable)obj).compare(obj2);result = ((Sortable)obj).compare(obj2); … … }}}}

Page 61: Inheritance and Polymorphism

Class DiagramsClass Diagrams

UML is a standard graphical notation UML is a standard graphical notation (language) for software modeling(language) for software modeling

Class diagrams are standard UML notation for Class diagrams are standard UML notation for representing classes and their relationshipsrepresenting classes and their relationships

Classes are represented by rectangles Classes are represented by rectangles containing their memberscontaining their members

Relationships are represented by arrowsRelationships are represented by arrows Several types of relations: associations, Several types of relations: associations,

aggregations, compositions, dependenciesaggregations, compositions, dependencies

Class diagrams visualize the class hierarchies Class diagrams visualize the class hierarchies obtained by inheriting classes and interfacesobtained by inheriting classes and interfaces

61

Page 62: Inheritance and Polymorphism

Class Diagrams – ExampleClass Diagrams – Example

62

Shape

#m Position:Point

structPoint

+m X:int+m Y:int

+Point

interfaceISurfaceCalculatable

+CalculateSurface:in t

Rectangle

-m W idth:int-m Height:in t

+Rectangle+CalculateSurface:in t

Square

-m S ize:in t

+Square+CalculateSurface:in t

FilledSquare

-m Color:Color

+FilledSquare

structColor

+m RedValue:byte+m G reenValue:byte+m BlueValue:byte

+Color

FilledRectangle

-m Color:Color

+FilledRectangle

Page 63: Inheritance and Polymorphism

QuestionsQuestions??

Inheritance and PolymorphismInheritance and Polymorphism

Page 64: Inheritance and Polymorphism

ProblemsProblems

1.1. Create an interface Create an interface IAnimalIAnimal that represents that represents an animal from the real world. Define the an animal from the real world. Define the method method talk()talk() that prints on the console the that prints on the console the specific scream of the animal ("jaff" for dogs, specific scream of the animal ("jaff" for dogs, "muaw" for cats, etc.). Add a boolean method "muaw" for cats, etc.). Add a boolean method coultEat(IAnimal)coultEat(IAnimal) that returns if given that returns if given animal eats any other animal.animal eats any other animal.

2.2. Create classes Create classes DogDog and and FrogFrog that implement that implement IAnimalIAnimal interface. Use interface. Use instanceofinstanceof operator operator in the method in the method couldEat(IAnimal)couldEat(IAnimal)..

3.3. Create an abstract class Create an abstract class CatCat that partially that partially implements the interface implements the interface IAnimalIAnimal..

64

Page 65: Inheritance and Polymorphism

ProblemsProblems

1.1. Inherit from the base abstract class Inherit from the base abstract class CatCat and and create subclasses create subclasses KittenKitten and and TomcatTomcat. These . These classes should fully implement the classes should fully implement the IAnimalIAnimal interface and define an implementation for the interface and define an implementation for the abstract methods from the class abstract methods from the class CatCat..

2.2. Write a class Write a class TestAnimalsTestAnimals that creates an that creates an array of animals (array of animals (IAnimal[]IAnimal[]): ): DogDog, , FrogFrog, , KittenKitten, , TomcatTomcat and calls their methods and calls their methods through through IAnimalIAnimal interface to ensure the interface to ensure the classes are implemented correctly.classes are implemented correctly.

65

Page 66: Inheritance and Polymorphism

HomeworkHomework

1.1. Create a class diagram for the hierarchy Create a class diagram for the hierarchy IAnimalIAnimal, , DogDog, , FrogFrog, , CatCat, , KittenKitten, , TomcatTomcat..

66

Page 67: Inheritance and Polymorphism

ProblemsProblems

1.1. Create a project, modeling a restaurant Create a project, modeling a restaurant system. You need to model the Restaurant, system. You need to model the Restaurant, People (Personnel and Clients), Orders from a People (Personnel and Clients), Orders from a client and Products for orders. Products could client and Products for orders. Products could be Meals or Beverages.be Meals or Beverages.

2.2. Client has one order and could buy many Client has one order and could buy many products. Orders are limited to a maximum products. Orders are limited to a maximum bill. No products could be added above the bill. No products could be added above the maximum.maximum.

3.3. Clients could pay with tip included (bill = price Clients could pay with tip included (bill = price + tip) + tip) 67

Page 68: Inheritance and Polymorphism

ProblemsProblems

1.1. Tasks:Tasks:

• Model the scheme and conventionsModel the scheme and conventions

• Find the top 5 clients with largest billsFind the top 5 clients with largest bills

• Sort clients by name in a collectionSort clients by name in a collection

• Design a function to find the day revenue of Design a function to find the day revenue of the restaurantthe restaurant

• Find the waiter with most tipsFind the waiter with most tips

68