SlideShare a Scribd company logo
1 of 68
Inheritance and PolymorphismInheritance and Polymorphism
Object-OrientedObject-Oriented
Programming inProgramming in
JavaJava
ContentsContents
1.1. Inheritance in JavaInheritance in Java
• Inheriting ClassesInheriting Classes
• TheThe supersuper ReferenceReference
• Overriding MethodsOverriding Methods
• PolymorphismPolymorphism
• TheThe instanceofinstanceof OperatorOperator
• final Methods and Classesfinal Methods and Classes
2
Contents (2)Contents (2)
1.1. Abstract ClassesAbstract Classes
• Abstract MethodsAbstract Methods
1.1. InterfacesInterfaces
• Defining InterfacesDefining Interfaces
• Implementing InterfacesImplementing Interfaces
1.1. Using Interfaces (Demo)Using Interfaces (Demo)
3
Access ModifiersAccess Modifiers
public, private, protected, defaultpublic, private, protected, default
(package)(package)
Access ModifiersAccess Modifiers
• The most common modifiers are the accessThe most common modifiers are the access
modifiers:modifiers:
• publicpublic
• privateprivate
• protectedprotected
• (default)(default)
• Access modifiers control which classesAccess modifiers control which classes
may use a membermay use a member
5
Access Modifiers RulesAccess Modifiers Rules
• The variables that you declare and useThe variables that you declare and use
within a class’s methods may not havewithin 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 isinner classes is publicpublic
• A member may have at most one accessA member may have at most one access
modifiermodifier
6
publicpublic
• The most generous access modifier isThe most generous access modifier is
publicpublic
• AA publicpublic class, variable, or method may beclass, variable, or method may be
used in any Java program withoutused in any Java program without
restrictionrestriction
• AnyAny publicpublic method may be overridden bymethod may be overridden by
any subclassany subclass
7
privateprivate
• The least generous access modifier isThe least generous access modifier is
privateprivate
• Top-level (that is, not inner) classes mayTop-level (that is, not inner) classes may
not be declarednot be declared privateprivate
• AA privateprivate variable or method may be usedvariable or method may be used
only by an instance of the class thatonly by an instance of the class that
declares the variable or methoddeclares the variable or method
8
protectedprotected
• Only variables and methods may beOnly variables and methods may be
declareddeclared protectedprotected
• AA protectedprotected member of a class ismember of a class is
available to all classes in the sameavailable to all classes in the same
package, just like a default memberpackage, just like a default member
• AA protectedprotected member of a class can bemember of a class can be
available in certain limited ways to allavailable in certain limited ways to all
subclasses of the class that owns thesubclasses of the class that owns the
protectedprotected member. It is visible inmember. It is visible in
subclasses in different packages too.subclasses in different packages too.9
(default)(default)
• DefaultDefault is the name of the access ofis the name of the access of
classes, variables, and methods if youclasses, 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 toA class’s default members are accessible to
any class in the same package as the classany class in the same package as the class
in questionin question
• A default method may be overridden by anyA default method may be overridden by any
subclass that is in the same package as thesubclass that is in the same package as the
superclasssuperclass 10
Applying Encapsulation inApplying Encapsulation in
JavaJava
• Instance variables should beInstance variables should be
declared asdeclared as privateprivate
• Only instance methods canOnly instance methods can
accessaccess privateprivate instanceinstance
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()
PackagesPackages
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
Grouping Classes in aGrouping Classes in a
PackagePackage
• Include theInclude the packagepackage keyword followed bykeyword followed by
one or more names separated by dots at theone 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 inIf 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 {
......
}}
Grouping Classes in aGrouping Classes in a
PackagePackage
• To run aTo run a main()main() method in a packagedmethod in a packaged
class requires:class requires:
• The CLASSPATH to contain the directoryThe 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 its
package namepackage name
15
java –cp . myPackage.MainClassjava –cp . myPackage.MainClass
The CLASSPATH withThe CLASSPATH with
PackagesPackages
• Includes the directory containing the top levelIncludes the directory containing the top level
of the package treeof the package tree
16
C:>setC:>set
CLASSPATH=E:Curriculumcoursesjavapracticesles06CLASSPATH=E:Curriculumcoursesjavapracticesles06
Package name .class location
CLASSPATH
Importing PackagesImporting Packages
• To use a class defined in other packageTo 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 theImport 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);
Inheritance andInheritance and
PolymorphismPolymorphism
Code Reuse TechniquesCode Reuse Techniques
Key Object-OrientedKey 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
Example of InheritanceExample of Inheritance

TheThe InventoryItemInventoryItem class defines methodsclass defines methods
and variablesand variables

Movie extendsMovie extends InventoryItemInventoryItem and can:and can:
− Add new variablesAdd new variables
− Add new methodsAdd new methods
− Override methods inOverride methods in InventoryItemInventoryItem classclass
InventoryItemInventoryItem
MovieMovie
Specifying Inheritance inSpecifying Inheritance in
JavaJava

Inheritance is achieved by specifying whichInheritance is achieved by specifying which
superclass the subclass extendssuperclass the subclass extends

Movie inherits all the variables and methodsMovie inherits all the variables and methods
ofof InventoryItemInventoryItem
public class InventoryItem {public class InventoryItem {
……
}}
public class Moviepublic class Movie extendsextends InventoryItem {InventoryItem {
……
}}
What Does a SubclassWhat Does a Subclass
Object Look Like?Object Look Like?

A subclass inherits all the instanceA subclass inherits all the instance
variables of its superclassvariables of its superclass
Movie
titletitle
lengthlength
priceprice
conditioncondition
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; …
}}
Default InitializationDefault Initialization

What happens when aWhat happens when a
subclass object is created?subclass object is created?

If no constructors are defined:If no constructors are defined:
− First, the defaultFirst, the default
parameterless constructor isparameterless constructor is
called in the superclasscalled in the superclass
− Then, the defaultThen, the default
parameterless constructor isparameterless constructor is
called in the subclasscalled in the subclass
Movie movie1 = new Movie();Movie movie1 = new Movie();
Movie
titletitle
lengthlength
priceprice
conditioncondition
TheThe supersuper ReferenceReference

Refers to the base classRefers to the base class

Is useful for calling base classIs useful for calling base class
constructorsconstructors
− Must be the first line in the derived classMust be the first line in the derived class
constructorconstructor

Can be used to call any base classCan be used to call any base class
methodsmethods
public class Movie extends InventoryItem {public class Movie extends InventoryItem {
public Movie() {public Movie() {
super("Matrix 8");super("Matrix 8");
}}
}}
TheThe supersuper ReferenceReference
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 classBase class
constructorconstructor
Calls baseCalls base
classclass
constructorconstructor
Using SuperclassUsing Superclass
ConstructorsConstructors
• UseUse super()super() to call a superclassto 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 InventoryItempublic 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;
} …} …
Specifying AdditionalSpecifying Additional
MethodsMethods

The superclass defines methods for allThe superclass defines methods for all
types oftypes of InventoryItemInventoryItem

The subclass can specify additionalThe subclass can specify additional
methods that are specific tomethods 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()…
Overriding SuperclassOverriding Superclass
MethodsMethods

A subclass inherits all the methods of itsA subclass inherits all the methods of its
superclasssuperclass

The subclass can override a method with itsThe subclass can override a method with its
own specialized versionown specialized version

Must have the same signature and semanticsMust have the same signature and semantics
as the superclass methodas the superclass method

In Java all methods are virtual (unlessIn Java all methods are virtual (unless
declared asdeclared as finalfinal))
− This forces theThis forces the late bindinglate binding mechanism onmechanism on
each method calleach method call
Overriding SuperclassOverriding 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;
}}
}}
}}
Invoking SuperclassInvoking Superclass
MethodsMethods

If a subclass overrides a method, it can stillIf a subclass overrides a method, it can still
call the original superclass methodcall the original superclass method

UseUse super.method()super.method() to call a superclassto call a superclass
method from the subclassmethod from the subclass
public 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);
}}
Treating a Subclass as ItsTreating a Subclass as Its
SuperclassSuperclass

A Java object instance of a subclass is plugA Java object instance of a subclass is plug
compatible with its superclass definitioncompatible with its superclass definition
− You can assign a subclass object to aYou can assign a subclass object to a
reference declared with the superclass:reference declared with the superclass:
− The compiler treats the object via itsThe compiler treats the object via its
reference, that is, in terms of its superclassreference, that is, in terms of its superclass
definitiondefinition
− The JVM creates a subclass object, executingThe JVM creates a subclass object, executing
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();
}}
Acme Video andAcme 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
ShoppingBasketShoppingBasket
void 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
Using theUsing the instanceofinstanceof
OperatorOperator

The true type of an object can beThe true type of an object can be
determined by using andetermined by using an instanceofinstanceof
operatoroperator

An object reference can be downcast to theAn 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();
}}
Limiting Methods andLimiting Methods and
Classes withClasses with finalfinal

A method can be marked asA method can be marked as finalfinal to preventto prevent
it from being overriddenit from being overridden

A whole class can be marked asA whole class can be marked as finalfinal toto
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) {
……
}}
When to Use Inheritance?When to Use Inheritance?

Inheritance should be used only for “is aInheritance should be used only for “is a
kind of” relationships:kind of” relationships:
− It must always be possible to substitute aIt must always be possible to substitute a
subclass object for a superclass objectsubclass object for a superclass object
− All methods in the superclass should makeAll methods in the superclass should make
sense in the subclasssense in the subclass

Inheritance for short-term convenienceInheritance for short-term convenience
leads to problems in the futureleads to problems in the future
Abstract Classes andAbstract Classes and
InterfacesInterfaces
Defining Abstract ClassesDefining Abstract Classes

Abstract classes model abstractAbstract 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 implementedAbstract methods must be implemented
by subclassesby subclasses
Abstract
superclass
Concrete
subclasses
InventoryItemInventoryItem
MovieMovie VCRVCR
Creating Abstract ClassesCreating Abstract Classes
in Javain Java

Use theUse the abstractabstract keyword to declare akeyword to declare a
class as abstractclass as abstract
publicpublic abstract classabstract class InventoryItem {InventoryItem {
private float price;private float price;
public boolean isRentable()…public boolean isRentable()…
}}
public class Moviepublic class Movie
extends InventoryItem {extends InventoryItem {
private String title;private String title;
public int getLength()…public int getLength()…
public class Vcrpublic class Vcr
extends InventoryItem {extends InventoryItem {
private int serialNbr;private int serialNbr;
public void setTimer()…public void setTimer()…
What Are AbstractWhat 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 theEach concrete subclass can implement the
method differentlymethod differently
Defining Abstract MethodsDefining Abstract Methods
in Javain Java

Use the abstract keyword to declare a methodUse the abstract keyword to declare a method
asas 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 withoutDeclare the structure of a class without
providing complete implementation of everyproviding complete implementation of every
methodmethod
public abstract class InventoryItem {public abstract class InventoryItem {
publicpublic abstractabstract boolean isRentable();boolean isRentable();
……
Defining and UsingDefining 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 areAll 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 mustA class that implements the interface must
provide code details for all the methods ofprovide code details for all the methods of
the interfacethe interface

A class can implement many interfaces butA class can implement many interfaces but
can extend only one classcan extend only one class
Example of InterfacesExample of Interfaces

Interfaces describe an aspect of behaviorInterfaces describe an aspect of behavior
that different classes requirethat different classes require

For example, classes that can be steeredFor example, classes that can be steered
support the “steerable” interfacesupport the “steerable” interface

Classes can be unrelatedClasses can be unrelated
SteerableNonsteerable
Creating an InterfaceCreating an Interface
− UseUse interfaceinterface keywordkeyword
− All methodsAll methods public abstractpublic abstract
− All variablesAll variables public static finalpublic static final
publicpublic 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);
}}
Implementing an InterfaceImplementing an Interface
• UseUse implementsimplements keywordkeyword
public class Yacht extends Boatpublic class Yacht extends Boat
implementsimplements SteerableSteerable
public void turnLeft(int deg) {…}public void turnLeft(int deg) {…}
public void turnRight(int deg) {…}public void turnRight(int deg) {…}
}}
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 theUses comparison rules known only to the
sortable objectsortable object

Supports good code reuseSupports good code reuse
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 classpublic class
MovieSortApplicationMovieSortApplication
public class Moviepublic class Movie
implements Sortableimplements Sortable
public interfacepublic interface
SortableSortable
public classpublic class
SortSort
MyApplicationMyApplication passespasses
an array of movies toan array of movies to
Sort.sortObjects()Sort.sortObjects()
11
2233
sortObjects()sortObjects() asks aasks a
movie to compare itselfmovie to compare itself
with another moviewith another movie
The movie returnsThe movie returns
the result of thethe result of the
comparisoncomparison
44
sortObjects()sortObjects()
returns thereturns the
sorted listsorted list
SortSort
MovieMovie
MyApplicationMyApplication
How the Sort Works?How the Sort Works?
TheThe SortableSortable
InterfaceInterface
• Specifies theSpecifies the compare()compare() methodmethod
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);
}}
TheThe SortSort ClassClass
• Implements sorting functionality: theImplements sorting functionality: the
methodmethod 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;
}}
}}
}}
}}
}}
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));
}}
}}
• ImplementsImplements SortableSortable
TheThe MovieMovie ClassClass
Using the SortUsing the Sort
• CallCall Sort.sortObjects(Sortable [])Sort.sortObjects(Sortable [])
with an array ofwith an array of MovieMovie as the argumentas 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);
}}
}}
Sorting with InterfacesSorting with Interfaces
Live DemoLive Demo
Inner ClassesInner Classes
What Are Inner Classes?What Are Inner Classes?
• Inner classes are classes defined within aInner 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:
• StaticStatic
• MemberMember
• LocalLocal
• AnonymousAnonymous
public class Outer { …public class Outer { …
class Inner { …class Inner { …
}}
}}
Defining Static InnerDefining 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 outerCan access only static members of the outer
classclass
Defining Member InnerDefining 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.thisOuter.this
......
}}
• Defined at class levelDefined at class level
• Instance of the outer is neededInstance of the outer is needed
• KeywordKeyword thisthis used to access the outer instanceused to access the outer instance
Defining Local InnerDefining 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 constructor
public 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; ...
}}
}}
}}
Defining Anonymous InnerDefining Anonymous Inner
ClassesClasses
• Defined at method levelDefined at method level
• Declared within a code blockDeclared within a code block
• Missing theMissing the classclass,, extendsextends, and, and
implementsimplements keywordskeywords
• 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(){
......
} )} )
}}
}}
UsingUsing instanceofinstanceof withwith
InterfacesInterfaces

Use theUse the instanceofinstanceof operator to check ifoperator to check if
an object implements an interfacean object implements an interface

Use downcasting to call methods definedUse downcasting to call methods defined
in the interfacein the interface
public void aMethod(Object obj) {public void aMethod(Object obj) {
……
if (objif (obj instanceofinstanceof Sortable) {Sortable) {
result = ((Sortable)obj).compare(obj2);result = ((Sortable)obj).compare(obj2);
……
}}
}}
Class DiagramsClass Diagrams

UML is a standard graphical notationUML is a standard graphical notation
(language) for software modeling(language) for software modeling

Class diagrams are standard UML notation forClass diagrams are standard UML notation for
representing classes and their relationshipsrepresenting classes and their relationships

Classes are represented by rectanglesClasses 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 hierarchiesClass diagrams visualize the class hierarchies
obtained by inheriting classes and interfacesobtained by inheriting classes and interfaces
61
Class Diagrams – ExampleClass Diagrams – Example
62
S h a p e
# m P o s it io n : P o in t
s t r u c t
P o in t
+ m X : in t
+ m Y : in t
+ P o in t
in t e r f a c e
IS u r f a c e C a lc u la t a b le
+ C a lc u la t e S u r f a c e : in t
R e c ta n g le
- m W id t h : in t
- m H e ig h t : in t
+ R e c ta n g le
+ C a lc u la t e S u r f a c e : in t
S q u a r e
- m S iz e : in t
+ S q u a r e
+ C a lc u la t e S u r f a c e : in t
F ille d S q u a r e
- m C o lo r : C o lo r
+ F ille d S q u a r e
s t r u c t
C o lo r
+ m R e d V a lu e : b y t e
+ m G r e e n V a lu e : b y t e
+ m B lu e V a lu e : b y t e
+ C o lo r
F ille d R e c ta n g le
- m C o lo r : C o lo r
+ F ille d R e c ta n g le
QuestionsQuestions??
Inheritance and PolymorphismInheritance and Polymorphism
ProblemsProblems
1.1. Create an interfaceCreate an interface IAnimalIAnimal that representsthat represents
an animal from the real world. Define thean animal from the real world. Define the
methodmethod talk()talk() that prints on the console thethat 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 giventhat returns if given
animal eats any other animal.animal eats any other animal.
2.2. Create classesCreate classes DogDog andand FrogFrog that implementthat implement
IAnimalIAnimal interface. Useinterface. Use instanceofinstanceof operatoroperator
in the methodin the method couldEat(IAnimal)couldEat(IAnimal)..
3.3. Create an abstract classCreate an abstract class CatCat that partiallythat partially
implements the interfaceimplements the interface IAnimalIAnimal..
64
ProblemsProblems
1.1. Inherit from the base abstract classInherit from the base abstract class CatCat andand
create subclassescreate subclasses KittenKitten andand TomcatTomcat. These. These
classes should fully implement theclasses should fully implement the IAnimalIAnimal
interface and define an implementation for theinterface and define an implementation for the
abstract methods from the classabstract methods from the class CatCat..
2.2. Write a classWrite a class TestAnimalsTestAnimals that creates anthat creates an
array of animals (array of animals (IAnimal[]IAnimal[]):): DogDog,, FrogFrog,,
KittenKitten,, TomcatTomcat and calls their methodsand calls their methods
throughthrough IAnimalIAnimal interface to ensure theinterface to ensure the
classes are implemented correctly.classes are implemented correctly.
65
HomeworkHomework
1.1. Create a class diagram for the hierarchyCreate a class diagram for the hierarchy
IAnimalIAnimal,, DogDog,, FrogFrog,, CatCat,, KittenKitten,, TomcatTomcat..
66
ProblemsProblems
1.1. Create a project, modeling a restaurantCreate 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 aPeople (Personnel and Clients), Orders from a
client and Products for orders. Products couldclient and Products for orders. Products could
be Meals or Beverages.be Meals or Beverages.
2.2. Client has one order and could buy manyClient has one order and could buy many
products. Orders are limited to a maximumproducts. Orders are limited to a maximum
bill. No products could be added above thebill. No products could be added above the
maximum.maximum.
3.3. Clients could pay with tip included (bill = priceClients could pay with tip included (bill = price
+ tip)+ tip) 67
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 ofDesign a function to find the day revenue of
the restaurantthe restaurant
• Find the waiter with most tipsFind the waiter with most tips
68

More Related Content

What's hot

What's hot (20)

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Generics
GenericsGenerics
Generics
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Inheritance
InheritanceInheritance
Inheritance
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Inner class
Inner classInner class
Inner class
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Python-DataAbstarction.pptx
Python-DataAbstarction.pptxPython-DataAbstarction.pptx
Python-DataAbstarction.pptx
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Packages in java
Packages in javaPackages in java
Packages in java
 

Similar to Inheritance and Polymorphism

Chap1 packages
Chap1 packagesChap1 packages
Chap1 packagesraksharao
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access SpecifierDeeptiJava
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
 
Chapter 03 enscapsulation
Chapter 03 enscapsulationChapter 03 enscapsulation
Chapter 03 enscapsulationNurhanna Aziz
 
Java class 3
Java class 3Java class 3
Java class 3Edureka!
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Core Java Introduction | Basics
Core Java Introduction  | BasicsCore Java Introduction  | Basics
Core Java Introduction | BasicsHùng Nguyễn Huy
 

Similar to Inheritance and Polymorphism (20)

Chap1 packages
Chap1 packagesChap1 packages
Chap1 packages
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Unit 3
Unit 3Unit 3
Unit 3
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Oops (inheritance&interface)
Oops (inheritance&interface)Oops (inheritance&interface)
Oops (inheritance&interface)
 
4th_class.pdf
4th_class.pdf4th_class.pdf
4th_class.pdf
 
Packages
PackagesPackages
Packages
 
Core java
Core javaCore java
Core java
 
9 cm604.26
9 cm604.269 cm604.26
9 cm604.26
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
Chapter 03 enscapsulation
Chapter 03 enscapsulationChapter 03 enscapsulation
Chapter 03 enscapsulation
 
Java class 3
Java class 3Java class 3
Java class 3
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Core Java Introduction | Basics
Core Java Introduction  | BasicsCore Java Introduction  | Basics
Core Java Introduction | Basics
 

More from BG Java EE Course (20)

Rich faces
Rich facesRich faces
Rich faces
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
JSTL
JSTLJSTL
JSTL
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
CSS
CSSCSS
CSS
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
 
Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
 

Recently uploaded

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Recently uploaded (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

Inheritance and Polymorphism

  • 1. Inheritance and PolymorphismInheritance and Polymorphism Object-OrientedObject-Oriented Programming inProgramming in JavaJava
  • 2. ContentsContents 1.1. Inheritance in JavaInheritance in Java • Inheriting ClassesInheriting Classes • TheThe supersuper ReferenceReference • Overriding MethodsOverriding Methods • PolymorphismPolymorphism • TheThe instanceofinstanceof OperatorOperator • final Methods and Classesfinal Methods and Classes 2
  • 3. Contents (2)Contents (2) 1.1. Abstract ClassesAbstract Classes • Abstract MethodsAbstract Methods 1.1. InterfacesInterfaces • Defining InterfacesDefining Interfaces • Implementing InterfacesImplementing Interfaces 1.1. Using Interfaces (Demo)Using Interfaces (Demo) 3
  • 4. Access ModifiersAccess Modifiers public, private, protected, defaultpublic, private, protected, default (package)(package)
  • 5. Access ModifiersAccess Modifiers • The most common modifiers are the accessThe most common modifiers are the access modifiers:modifiers: • publicpublic • privateprivate • protectedprotected • (default)(default) • Access modifiers control which classesAccess modifiers control which classes may use a membermay use a member 5
  • 6. Access Modifiers RulesAccess Modifiers Rules • The variables that you declare and useThe variables that you declare and use within a class’s methods may not havewithin 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 isinner classes is publicpublic • A member may have at most one accessA member may have at most one access modifiermodifier 6
  • 7. publicpublic • The most generous access modifier isThe most generous access modifier is publicpublic • AA publicpublic class, variable, or method may beclass, variable, or method may be used in any Java program withoutused in any Java program without restrictionrestriction • AnyAny publicpublic method may be overridden bymethod may be overridden by any subclassany subclass 7
  • 8. privateprivate • The least generous access modifier isThe least generous access modifier is privateprivate • Top-level (that is, not inner) classes mayTop-level (that is, not inner) classes may not be declarednot be declared privateprivate • AA privateprivate variable or method may be usedvariable or method may be used only by an instance of the class thatonly by an instance of the class that declares the variable or methoddeclares the variable or method 8
  • 9. protectedprotected • Only variables and methods may beOnly variables and methods may be declareddeclared protectedprotected • AA protectedprotected member of a class ismember of a class is available to all classes in the sameavailable to all classes in the same package, just like a default memberpackage, just like a default member • AA protectedprotected member of a class can bemember of a class can be available in certain limited ways to allavailable in certain limited ways to all subclasses of the class that owns thesubclasses of the class that owns the protectedprotected member. It is visible inmember. It is visible in subclasses in different packages too.subclasses in different packages too.9
  • 10. (default)(default) • DefaultDefault is the name of the access ofis the name of the access of classes, variables, and methods if youclasses, 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 toA class’s default members are accessible to any class in the same package as the classany class in the same package as the class in questionin question • A default method may be overridden by anyA default method may be overridden by any subclass that is in the same package as thesubclass that is in the same package as the superclasssuperclass 10
  • 11. Applying Encapsulation inApplying Encapsulation in JavaJava • Instance variables should beInstance variables should be declared asdeclared as privateprivate • Only instance methods canOnly instance methods can accessaccess privateprivate instanceinstance 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()
  • 13. 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
  • 14. Grouping Classes in aGrouping Classes in a PackagePackage • Include theInclude the packagepackage keyword followed bykeyword followed by one or more names separated by dots at theone 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 inIf 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 { ...... }}
  • 15. Grouping Classes in aGrouping Classes in a PackagePackage • To run aTo run a main()main() method in a packagedmethod in a packaged class requires:class requires: • The CLASSPATH to contain the directoryThe 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 its package namepackage name 15 java –cp . myPackage.MainClassjava –cp . myPackage.MainClass
  • 16. The CLASSPATH withThe CLASSPATH with PackagesPackages • Includes the directory containing the top levelIncludes the directory containing the top level of the package treeof the package tree 16 C:>setC:>set CLASSPATH=E:Curriculumcoursesjavapracticesles06CLASSPATH=E:Curriculumcoursesjavapracticesles06 Package name .class location CLASSPATH
  • 17. Importing PackagesImporting Packages • To use a class defined in other packageTo 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 theImport 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);
  • 18. Inheritance andInheritance and PolymorphismPolymorphism Code Reuse TechniquesCode Reuse Techniques
  • 19. Key Object-OrientedKey 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
  • 20. Example of InheritanceExample of Inheritance  TheThe InventoryItemInventoryItem class defines methodsclass defines methods and variablesand variables  Movie extendsMovie extends InventoryItemInventoryItem and can:and can: − Add new variablesAdd new variables − Add new methodsAdd new methods − Override methods inOverride methods in InventoryItemInventoryItem classclass InventoryItemInventoryItem MovieMovie
  • 21. Specifying Inheritance inSpecifying Inheritance in JavaJava  Inheritance is achieved by specifying whichInheritance is achieved by specifying which superclass the subclass extendssuperclass the subclass extends  Movie inherits all the variables and methodsMovie inherits all the variables and methods ofof InventoryItemInventoryItem public class InventoryItem {public class InventoryItem { …… }} public class Moviepublic class Movie extendsextends InventoryItem {InventoryItem { …… }}
  • 22. What Does a SubclassWhat Does a Subclass Object Look Like?Object Look Like?  A subclass inherits all the instanceA subclass inherits all the instance variables of its superclassvariables of its superclass Movie titletitle lengthlength priceprice conditioncondition 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; … }}
  • 23. Default InitializationDefault Initialization  What happens when aWhat happens when a subclass object is created?subclass object is created?  If no constructors are defined:If no constructors are defined: − First, the defaultFirst, the default parameterless constructor isparameterless constructor is called in the superclasscalled in the superclass − Then, the defaultThen, the default parameterless constructor isparameterless constructor is called in the subclasscalled in the subclass Movie movie1 = new Movie();Movie movie1 = new Movie(); Movie titletitle lengthlength priceprice conditioncondition
  • 24. TheThe supersuper ReferenceReference  Refers to the base classRefers to the base class  Is useful for calling base classIs useful for calling base class constructorsconstructors − Must be the first line in the derived classMust be the first line in the derived class constructorconstructor  Can be used to call any base classCan be used to call any base class methodsmethods public class Movie extends InventoryItem {public class Movie extends InventoryItem { public Movie() {public Movie() { super("Matrix 8");super("Matrix 8"); }} }}
  • 25. TheThe supersuper ReferenceReference 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 classBase class constructorconstructor Calls baseCalls base classclass constructorconstructor
  • 26. Using SuperclassUsing Superclass ConstructorsConstructors • UseUse super()super() to call a superclassto 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 InventoryItempublic 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; } …} …
  • 27. Specifying AdditionalSpecifying Additional MethodsMethods  The superclass defines methods for allThe superclass defines methods for all types oftypes of InventoryItemInventoryItem  The subclass can specify additionalThe subclass can specify additional methods that are specific tomethods 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()…
  • 28. Overriding SuperclassOverriding Superclass MethodsMethods  A subclass inherits all the methods of itsA subclass inherits all the methods of its superclasssuperclass  The subclass can override a method with itsThe subclass can override a method with its own specialized versionown specialized version  Must have the same signature and semanticsMust have the same signature and semantics as the superclass methodas the superclass method  In Java all methods are virtual (unlessIn Java all methods are virtual (unless declared asdeclared as finalfinal)) − This forces theThis forces the late bindinglate binding mechanism onmechanism on each method calleach method call
  • 29. Overriding SuperclassOverriding 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; }} }} }}
  • 30. Invoking SuperclassInvoking Superclass MethodsMethods  If a subclass overrides a method, it can stillIf a subclass overrides a method, it can still call the original superclass methodcall the original superclass method  UseUse super.method()super.method() to call a superclassto call a superclass method from the subclassmethod from the subclass public 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); }}
  • 31. Treating a Subclass as ItsTreating a Subclass as Its SuperclassSuperclass  A Java object instance of a subclass is plugA Java object instance of a subclass is plug compatible with its superclass definitioncompatible with its superclass definition − You can assign a subclass object to aYou can assign a subclass object to a reference declared with the superclass:reference declared with the superclass: − The compiler treats the object via itsThe compiler treats the object via its reference, that is, in terms of its superclassreference, that is, in terms of its superclass definitiondefinition − The JVM creates a subclass object, executingThe JVM creates a subclass object, executing 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(); }}
  • 32. Acme Video andAcme 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
  • 33. ShoppingBasketShoppingBasket void 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
  • 34. Using theUsing the instanceofinstanceof OperatorOperator  The true type of an object can beThe true type of an object can be determined by using andetermined by using an instanceofinstanceof operatoroperator  An object reference can be downcast to theAn 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(); }}
  • 35. Limiting Methods andLimiting Methods and Classes withClasses with finalfinal  A method can be marked asA method can be marked as finalfinal to preventto prevent it from being overriddenit from being overridden  A whole class can be marked asA whole class can be marked as finalfinal toto 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) { …… }}
  • 36. When to Use Inheritance?When to Use Inheritance?  Inheritance should be used only for “is aInheritance should be used only for “is a kind of” relationships:kind of” relationships: − It must always be possible to substitute aIt must always be possible to substitute a subclass object for a superclass objectsubclass object for a superclass object − All methods in the superclass should makeAll methods in the superclass should make sense in the subclasssense in the subclass  Inheritance for short-term convenienceInheritance for short-term convenience leads to problems in the futureleads to problems in the future
  • 37. Abstract Classes andAbstract Classes and InterfacesInterfaces
  • 38. Defining Abstract ClassesDefining Abstract Classes  Abstract classes model abstractAbstract 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 implementedAbstract methods must be implemented by subclassesby subclasses Abstract superclass Concrete subclasses InventoryItemInventoryItem MovieMovie VCRVCR
  • 39. Creating Abstract ClassesCreating Abstract Classes in Javain Java  Use theUse the abstractabstract keyword to declare akeyword to declare a class as abstractclass as abstract publicpublic abstract classabstract class InventoryItem {InventoryItem { private float price;private float price; public boolean isRentable()…public boolean isRentable()… }} public class Moviepublic class Movie extends InventoryItem {extends InventoryItem { private String title;private String title; public int getLength()…public int getLength()… public class Vcrpublic class Vcr extends InventoryItem {extends InventoryItem { private int serialNbr;private int serialNbr; public void setTimer()…public void setTimer()…
  • 40. What Are AbstractWhat 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 theEach concrete subclass can implement the method differentlymethod differently
  • 41. Defining Abstract MethodsDefining Abstract Methods in Javain Java  Use the abstract keyword to declare a methodUse the abstract keyword to declare a method asas 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 withoutDeclare the structure of a class without providing complete implementation of everyproviding complete implementation of every methodmethod public abstract class InventoryItem {public abstract class InventoryItem { publicpublic abstractabstract boolean isRentable();boolean isRentable(); ……
  • 42. Defining and UsingDefining 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 areAll 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 mustA class that implements the interface must provide code details for all the methods ofprovide code details for all the methods of the interfacethe interface  A class can implement many interfaces butA class can implement many interfaces but can extend only one classcan extend only one class
  • 43. Example of InterfacesExample of Interfaces  Interfaces describe an aspect of behaviorInterfaces describe an aspect of behavior that different classes requirethat different classes require  For example, classes that can be steeredFor example, classes that can be steered support the “steerable” interfacesupport the “steerable” interface  Classes can be unrelatedClasses can be unrelated SteerableNonsteerable
  • 44. Creating an InterfaceCreating an Interface − UseUse interfaceinterface keywordkeyword − All methodsAll methods public abstractpublic abstract − All variablesAll variables public static finalpublic static final publicpublic 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); }}
  • 45. Implementing an InterfaceImplementing an Interface • UseUse implementsimplements keywordkeyword public class Yacht extends Boatpublic class Yacht extends Boat implementsimplements SteerableSteerable public void turnLeft(int deg) {…}public void turnLeft(int deg) {…} public void turnRight(int deg) {…}public void turnRight(int deg) {…} }}
  • 46. 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 theUses comparison rules known only to the sortable objectsortable object  Supports good code reuseSupports good code reuse
  • 47. 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 classpublic class MovieSortApplicationMovieSortApplication public class Moviepublic class Movie implements Sortableimplements Sortable public interfacepublic interface SortableSortable public classpublic class SortSort
  • 48. MyApplicationMyApplication passespasses an array of movies toan array of movies to Sort.sortObjects()Sort.sortObjects() 11 2233 sortObjects()sortObjects() asks aasks a movie to compare itselfmovie to compare itself with another moviewith another movie The movie returnsThe movie returns the result of thethe result of the comparisoncomparison 44 sortObjects()sortObjects() returns thereturns the sorted listsorted list SortSort MovieMovie MyApplicationMyApplication How the Sort Works?How the Sort Works?
  • 49. TheThe SortableSortable InterfaceInterface • Specifies theSpecifies the compare()compare() methodmethod 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); }}
  • 50. TheThe SortSort ClassClass • Implements sorting functionality: theImplements sorting functionality: the methodmethod 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; }} }} }} }} }}
  • 51. 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)); }} }} • ImplementsImplements SortableSortable TheThe MovieMovie ClassClass
  • 52. Using the SortUsing the Sort • CallCall Sort.sortObjects(Sortable [])Sort.sortObjects(Sortable []) with an array ofwith an array of MovieMovie as the argumentas 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); }} }}
  • 53. Sorting with InterfacesSorting with Interfaces Live DemoLive Demo
  • 55. What Are Inner Classes?What Are Inner Classes? • Inner classes are classes defined within aInner 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: • StaticStatic • MemberMember • LocalLocal • AnonymousAnonymous public class Outer { …public class Outer { … class Inner { …class Inner { … }} }}
  • 56. Defining Static InnerDefining 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 outerCan access only static members of the outer classclass
  • 57. Defining Member InnerDefining 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.thisOuter.this ...... }} • Defined at class levelDefined at class level • Instance of the outer is neededInstance of the outer is needed • KeywordKeyword thisthis used to access the outer instanceused to access the outer instance
  • 58. Defining Local InnerDefining 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 constructor public 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; ... }} }} }}
  • 59. Defining Anonymous InnerDefining Anonymous Inner ClassesClasses • Defined at method levelDefined at method level • Declared within a code blockDeclared within a code block • Missing theMissing the classclass,, extendsextends, and, and implementsimplements keywordskeywords • 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(){ ...... } )} ) }} }}
  • 60. UsingUsing instanceofinstanceof withwith InterfacesInterfaces  Use theUse the instanceofinstanceof operator to check ifoperator to check if an object implements an interfacean object implements an interface  Use downcasting to call methods definedUse downcasting to call methods defined in the interfacein the interface public void aMethod(Object obj) {public void aMethod(Object obj) { …… if (objif (obj instanceofinstanceof Sortable) {Sortable) { result = ((Sortable)obj).compare(obj2);result = ((Sortable)obj).compare(obj2); …… }} }}
  • 61. Class DiagramsClass Diagrams  UML is a standard graphical notationUML is a standard graphical notation (language) for software modeling(language) for software modeling  Class diagrams are standard UML notation forClass diagrams are standard UML notation for representing classes and their relationshipsrepresenting classes and their relationships  Classes are represented by rectanglesClasses 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 hierarchiesClass diagrams visualize the class hierarchies obtained by inheriting classes and interfacesobtained by inheriting classes and interfaces 61
  • 62. Class Diagrams – ExampleClass Diagrams – Example 62 S h a p e # m P o s it io n : P o in t s t r u c t P o in t + m X : in t + m Y : in t + P o in t in t e r f a c e IS u r f a c e C a lc u la t a b le + C a lc u la t e S u r f a c e : in t R e c ta n g le - m W id t h : in t - m H e ig h t : in t + R e c ta n g le + C a lc u la t e S u r f a c e : in t S q u a r e - m S iz e : in t + S q u a r e + C a lc u la t e S u r f a c e : in t F ille d S q u a r e - m C o lo r : C o lo r + F ille d S q u a r e s t r u c t C o lo r + m R e d V a lu e : b y t e + m G r e e n V a lu e : b y t e + m B lu e V a lu e : b y t e + C o lo r F ille d R e c ta n g le - m C o lo r : C o lo r + F ille d R e c ta n g le
  • 64. ProblemsProblems 1.1. Create an interfaceCreate an interface IAnimalIAnimal that representsthat represents an animal from the real world. Define thean animal from the real world. Define the methodmethod talk()talk() that prints on the console thethat 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 giventhat returns if given animal eats any other animal.animal eats any other animal. 2.2. Create classesCreate classes DogDog andand FrogFrog that implementthat implement IAnimalIAnimal interface. Useinterface. Use instanceofinstanceof operatoroperator in the methodin the method couldEat(IAnimal)couldEat(IAnimal).. 3.3. Create an abstract classCreate an abstract class CatCat that partiallythat partially implements the interfaceimplements the interface IAnimalIAnimal.. 64
  • 65. ProblemsProblems 1.1. Inherit from the base abstract classInherit from the base abstract class CatCat andand create subclassescreate subclasses KittenKitten andand TomcatTomcat. These. These classes should fully implement theclasses should fully implement the IAnimalIAnimal interface and define an implementation for theinterface and define an implementation for the abstract methods from the classabstract methods from the class CatCat.. 2.2. Write a classWrite a class TestAnimalsTestAnimals that creates anthat creates an array of animals (array of animals (IAnimal[]IAnimal[]):): DogDog,, FrogFrog,, KittenKitten,, TomcatTomcat and calls their methodsand calls their methods throughthrough IAnimalIAnimal interface to ensure theinterface to ensure the classes are implemented correctly.classes are implemented correctly. 65
  • 66. HomeworkHomework 1.1. Create a class diagram for the hierarchyCreate a class diagram for the hierarchy IAnimalIAnimal,, DogDog,, FrogFrog,, CatCat,, KittenKitten,, TomcatTomcat.. 66
  • 67. ProblemsProblems 1.1. Create a project, modeling a restaurantCreate 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 aPeople (Personnel and Clients), Orders from a client and Products for orders. Products couldclient and Products for orders. Products could be Meals or Beverages.be Meals or Beverages. 2.2. Client has one order and could buy manyClient has one order and could buy many products. Orders are limited to a maximumproducts. Orders are limited to a maximum bill. No products could be added above thebill. No products could be added above the maximum.maximum. 3.3. Clients could pay with tip included (bill = priceClients could pay with tip included (bill = price + tip)+ tip) 67
  • 68. 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 ofDesign a function to find the day revenue of the restaurantthe restaurant • Find the waiter with most tipsFind the waiter with most tips 68

Editor's Notes

  1. A class’s members are The class itself Its member variables Its methods and constructors Its nested classes
  2. The variables that you declare and use within a class’s methods may not have access modifiers - With rare exceptions, the only variables that may be controlled by access modifiers are class-level variables. The only access modifier permitted to non-inner classes is public - there is no such thing as a protected or private top-level class. Inner classes are discussed in Module &amp;quot;Objects and Classes&amp;quot;. A member may have at most one access modifier - If a member has no access modifier, its access defaults to a mode that, unfortunately, has no standardized name. The default access mode is known variously as friendly, package, or default. In this course, we use the term default.
  3. An application declares its main() method to be public so that main() can be invoked from any Java runtime environment.
  4. A protected member of a class can be available in certain limited ways to all subclasses of the class that owns the protected member. - This access is provided even to subclasses that reside in a different package from the class that owns the protected member.
  5. Default is not a Java keyword; it is simply a name that is given to the access level that results from not specifying an access modifier.
  6. Encapsulation Encapsulation is a key concept in object-oriented programming. A well-defined class should decouple its public interface from its internal implementation. To achieve this, all instance variables of a class should be made private to hide them from users of the class. Only the instance methods of a class can access the private instance variables of that class. Users of the class must invoke one of the public methods of the class to access (get) or change (set) the state of an object. For example, if the Movie class is properly encapsulated, it is impossible for a user of the Movie class to directly access instance variables such as title and rating. The Benefits of Encapsulation As a class evolves, there is every chance that you will need to modify the way in which the class is implemented internally. However, as long as you preserve the same interface to the class, the rest of the program will not need to be modified at all. You preserve the interface by retaining the same public instance methods with exactly the same signatures or parameter lists. By maintaining this encapsulation, you will not break any existing code that uses the Movie class.
  7. What Is a Package? A package is a container of classes that are logically related, either by application or function. A package consists of all the Java classes within a directory on the file system. Package names and used within a Java run-time environment to manage the uniqueness of identifiers as well as to control access from other classes. They also help by segmenting related parts of complex applications into manageable parts. Namespace The Java VM uses a construct called namespace to manage identifier names within a Java program. A namespace is a chunk of memory allocated specifically to manage objects. Objects are placed in specific namespaces depending on the source of the code. For example, a class loaded from a local package is loaded into one namespace while one loaded from a network source goes into another separate namespace. Identifier names must be unique within a namespace. Without the internal namespace construct, identifier names would need to be unique across all Java classes. In other words, if the J2SE or any other class you need uses an identifier named count, your program could not define a variable named count. Java uses namespaces to manage the identifier names so that you don’t have to worry about what names are used by other classes. You have to manage uniqueness only within your program.
  8. Using Packages The package represents the organization of the Java byte code of classes and interfaces. It is not the source code organization, represented by the .java files. The Java compiler reads and uses any needed packaged classes, you specify. Important: The CLASSPATH environmental variable is extremely critical when using packages. Most runtime problems with code using packages emanate from a missing directory in the CLASSPATH environment. When running the Java application, you must include the package name in the command. c:\&amp;gt;java &amp;lt;package_name&amp;gt;.&amp;lt;class&amp;gt; c:\&amp;gt;java practice06.MaintainCustomers If a class is included in a package, the compiler can be requested to put the class file in a subdirectory reflecting the package name. To create the package directory names during compile time, use the –d option. For example, if you compile a class called RentalItem in a package called rentals as follows: javac -d c:\acmevideo RentItem.java then the class file created is called c:\acmevideo\rentals\RentItem.class. The default behavior for the javac command without the -d option is to put the class file in the same directory as the source file.
  9. Using Packages The package represents the organization of the Java byte code of classes and interfaces. It is not the source code organization, represented by the .java files. The Java compiler reads and uses any needed packaged classes, you specify. Important: The CLASSPATH environmental variable is extremely critical when using packages. Most runtime problems with code using packages emanate from a missing directory in the CLASSPATH environment. When running the Java application, you must include the package name in the command. c:\&amp;gt;java &amp;lt;package_name&amp;gt;.&amp;lt;class&amp;gt; c:\&amp;gt;java practice06.MaintainCustomers If a class is included in a package, the compiler can be requested to put the class file in a subdirectory reflecting the package name. To create the package directory names during compile time, use the –d option. For example, if you compile a class called RentalItem in a package called rentals as follows: javac -d c:\acmevideo RentItem.java then the class file created is called c:\acmevideo\rentals\RentItem.class. The default behavior for the javac command without the -d option is to put the class file in the same directory as the source file.
  10. Setting the CLASSPATH with Packages The CLASSPATH must contain the directory/path containing the top level name your classes package tree. For example, suppose you want the Java interpreter to be able to find classes in the package practice06. If the path to the practice06 classes directory is: E:\Curriculum\courses\java\practices\les06\practice06 You would set the CLASSPATH variable from an operating system prompt as follows: set CLASSPATH=E:\Curriculum\courses\java\practices\les06 Once you exit a DOS prompt the CLASSPATH reverts back to the permanent settings. The CLASSPATH is used by both the compiler and the class loader in the Interpreter (JVM) to locate, resolve references to class names and load the classes into memory at run time. The CLASSPATH can include: A list directory names (separated by semicolon’s in Windows, and colons in UNIX): The classes are in a package tree relative to any of the directories in the list A zip/jar file name fully qualified with its path name The classes in these files must be zipped with the path names derived from the directories formed by their package names. Reminder: The directory containing the root name of a package tree must be added to the CLASSPATH! Consider putting the CLASSPATH information in the command window or even the java command, rather than hard coding it in the environment, for example: java -classpath E:\Curriculum\courses\java\practices\les06 practice06.AddCustomers
  11. Instructor Note This lesson reviews the inheritance and polymorphism properties that were introduced in lesson 2, but from a Java language point of view. Schedule:TimingTopic 50 minutesLecture 40 minutesPractice 90 minutesTotal
  12. What Is Inheritance? Inheritance defines a relationship between classes where one class shares the data structure and behaviors of another class. Inheritance is a valuable technique because it enables and encourages software reuse by allowing you to create a new class based on the properties of an existing class. As a result, the developer is able to achieve greater productivity than would otherwise be possible. Inheritance and Constructors Constructors are blocks of code that are executed when an object of that class is created. By using an inheritance model, each subclass has access to the superclass’s constructor. Any common constructor code can be put in the superclass constructor and called by the subclass. This technique minimizes the need for duplicated code and provides for consistent object creation. Polymorphism Polymorphism describes the ability of Java to execute a specific method based on the object reference used in the call. Using this technique, you can define a method in the superclass and override it in the appropriate subclass. You can now write method calls to the superclass, and if the method is overridden in a subclass, Java will automatically call the right method. This is a very powerful construct that allows you to define superclass methods before knowing the details of any subclasses.
  13. The InventoryItem Class The InventoryItem class defines the attributes and methods that are relevant for all kinds of inventory items. The attributes and methods may include: Attributes, such as the date of purchase, purchase cost, and condition Methods, such as calculating a deposit, changing the condition, and setting the price Dealing with Different Types of InventoryItem Depending on what you are trying to do in your program, you might need to represent a specific type of InventoryItem in a particular way. You can use inheritance to define a separate subclass of InventoryItem for each different type of InventoryItem. For example, you might define classes such as Movie, Game, and VCR. Each subclass automatically inherits the attributes and methods of InventoryItem, but can provide additional attributes and methods as necessary. For example, the Movie class might define the following additional attributes and methods: Attributes, such as the title of the movie, the director, and the running length Methods, such as reviewing the movie, setting the rating, and so on Subclasses can also override a method from the superclass if they want to provide more specialized behavior for the method. In this example, the movie could override the InventoryItem calculating a deposit method. A movie may have an additional amount calculated into the deposit.
  14. Specifying Inheritance in Java When you define a subclass, you need to provide code only for the features in the subclass that are different from those of the superclass. In a very real way, the subclass is extending the superclass. The syntax for specifying inheritance in Java makes use of a keyword extends. For example: public class InventoryItem { // Definition of the InventoryItem class } public class Movie extends InventoryItem { // Additional methods and attributes, to distinguish a // Movie from other types of InventoryItem } Characteristics of Inheritance in Java If you have experience with another OO language such as C++, note that Java allows only single inheritance. In other words, a class can specify only one immediate superclass. Also, remember that all classes in Java are automatically inherited from the root class called Object, which sits at the top of the inheritance tree. If a class does not specify an explicit superclass, as is the case with InventoryItem in the slide, then the class is deemed to extend directly from Object, as if it were defined as follows: public class InventoryItem extends Object { …
  15. Variables in the Superclass and Subclass The superclass defines the variables that are relevant for all kinds of InventoryItem , such as the purchase date and condition. The subclass, Movie, inherits these variables for free and has to specify only the Movie-specific variables, such as the title. What Does an Object Look Like? If you create a plain InventoryItem object, it just contains the instance variables defined in InventoryItem : InventoryItem i = new InventoryItem (…); //an InventoryItem has a price and condition However, if you create a Movie object, it contains four instance variables: the two inherited from InventoryItem , plus two added in Movie: Movie m = new Movie(…); // A Movie object has a price and condition, because a // Movie is a kind of InventoryItem. // The Movie object also has a title and length. Declaring Instance Variables as private Instance variables should normally be declared as private, which means that instances of subclasses inherit the values, but cannot access them directly. As we saw earlier, you must define methods to access private variables. You can define methods in the subclass or inherit them from the superclass.
  16. Default Provision of Constructors A class does not inherit any constructors from its superclass. Therefore, the InventoryItem class has only the constructors explicitly declared in its definition or a default no-arg constructor if there are no other constructors at all. What Happens When a Subclass Object Is Created? The example in the slide creates a Movie object. For the moment, assume that neither the Movie class nor the InventoryItem class provides any constructors; all they have is the default no-arg constructor provided automatically by Java. What happens when a Movie object is created? Objects are always constructed from the top class down to the bottom class; that is, from the Object class down to the class that is being instantiated using new. This ensures that a constructor in a subclass can always rely on proper construction of its superclass. In the example, when you create a Movie object, the no-arg constructor of InventoryItem will be called first to initialize the InventoryItem instance variables with default values. The price will be set to 0 and condition will be set to its default‘excellent’. Once the superclass has been initialized, the no-arg constructor of Movie will then be called to initialize the title and length instance variable with default values.
  17. The super Reference The super reference is useful only when a class has an ancestor. A subclass inherits all of the superclass methods and variables as well as creates its own. Methods in the superclass may be overridden in the subclass by creating methods with the same name and signature in the subclass. The super keyword allows you to specifically access methods in the superclass even though they have been overridden in the subclass. Calling Constructors One of the more common uses of super is to call the superclass constructor. When the superclass was designed, it probably had a constructor to insure proper initialization of any new objects. Because a subclass inherits all of the superclass variables, they need to be initialized for subclass objects as well. The super keyword allows you to use the constructor code in the superclass without having to duplicate the code in each subclass. Add the super reference within the subclass constructor to access the superclass constructor: subclass() { // constructor for the subclass super(); // call the superclass constructor … ; // subclass specific constructor code } The syntax rule is that the super keyword must be the first line in the subclass constructor. The super keyword may also be used to call any superclass methods.
  18. super Reference Example In the example, there are initialization routines that should happen for all inventory items. Those routines are placed in the InventoryItem constructor. These routines should be used regardless of the type of InventoryItem being constructed, whether it is a Movie, Game, or a Book. There are also constructors in each of the subclasses to take care of subclass-specific routines. The Movie constructor reuses the InventoryItem constructor by referencing it with the super keyword. This statement is the first statement in the Movie constructor and may be followed by whatever other statements are necessary to fully construct a Movie object.
  19. Nondefault Initialization with Inheritance The superclass and subclass often have constructors that take arguments. For example, InventoryItem might have a constructor that takes arguments to initialize price and condition: public InventoryItem (float p, String cond) { price = p; condition = cond; } Likewise, the Movie class might have a constructor that takes enough arguments to initialize its attributes. This is where things get interesting. A Movie object has three attributes: price and condition inherited from InventoryItem , plus title, defined in Movie itself. The Movie constructor might therefore take three arguments: public Movie(float p, String cond, String t) { … } Rather than initializing price and condition explicitly, all the Movie constructor has to do is call the superclass constructor. This can be achieved by using the super keyword; the call to super(…) must be the first statement in the constructor. public Movie(float p, String cond, String t) { super(p, cond); // Call superclass constructor title = t; // Initialize Movie-specific attributes If you do not explicitly call super(…), the compiler calls the superclass no-arg constructor by default. If the superclass does not have a no-arg constructor, a compiler error occurs.
  20. Methods in the Superclass and Subclass The slide shows some of the methods declared in the superclass and the subclass. The superclass defines the methods that are relevant for all kinds of InventoryItem, such as the ability to calculate a deposit or the due date for the item. The subclass, Movie, inherits these methods from the superclass and has to add only the Movie-specific methods, such as getting the title and getting the length. What Methods Can Be Called When you create an object, you can call any of its public methods plus any public methods declared in its superclass. For example, if you create an InventoryItem object, you can call the public methods defined in InventoryItem , plus any public methods defined in its superclass, Object: InventoryItem i = new InventoryItem (…); i.getId();// Call a public method in InventoryItem i.getClass(…); // Call a public method in Object If you create a Movie object, you can call any public method defined in Movie, InventoryItem, or Object: Movie m = new movie(…);// Create a Movie object m.getTitle();// Call a public method in Movie m.getId();// Call a public method in InventoryItem m.getClass(…);// Call a public method in Object
  21. Overriding Superclass Methods A subclass inherits all of the methods of its superclass. However, a subclass can modify the behavior of a method in a superclass by overriding it, as shown in the slide. To override a superclass method, the subclass defines a method with exactly the same signature and return type as a method somewhere above it in the inheritance hierarchy. The method in the subclass effectively hides the method in the superclass. It is important to make sure that the method in the subclass has the same semantics as the one it is overriding. Which Method Is Called? In the example shown in the slide, the InventoryItem class provides a calcDeposit() method, and the Vcr class overrides it with a more specialized version. If you create an InventoryItem object and call calcDeposit(), it calls the InventoryItem version of the method. If you create a Movie object and call calcDeposit(), it calls the Movie version of the method. Overriding and Overloading Do not confuse “method overloading” with “method overriding”: Method overloading is where you define multiple methods with different signatures. Overloaded methods are resolved at compile time, based on the arguments you supply. Method overriding is where you provide a method with exactly the same signature as a method in a superclass. Overridden methods are resolved at run time, unlike overloaded methods. This is polymorphism, and is discussed later in the lesson.
  22. Overriding Superclass Methods A subclass inherits all of the methods of its superclass. However, a subclass can modify the behavior of a method in a superclass by overriding it, as shown in the slide. To override a superclass method, the subclass defines a method with exactly the same signature and return type as a method somewhere above it in the inheritance hierarchy. The method in the subclass effectively hides the method in the superclass. It is important to make sure that the method in the subclass has the same semantics as the one it is overriding. Which Method Is Called? In the example shown in the slide, the InventoryItem class provides a calcDeposit() method, and the Vcr class overrides it with a more specialized version. If you create an InventoryItem object and call calcDeposit(), it calls the InventoryItem version of the method. If you create a Movie object and call calcDeposit(), it calls the Movie version of the method. Overriding and Overloading Do not confuse “method overloading” with “method overriding”: Method overloading is where you define multiple methods with different signatures. Overloaded methods are resolved at compile time, based on the arguments you supply. Method overriding is where you provide a method with exactly the same signature as a method in a superclass. Overridden methods are resolved at run time, unlike overloaded methods. This is polymorphism, and is discussed later in the lesson.
  23. Calling an Overridden Method from the Client Program As previously mentioned, when a subclass overrides a method in a superclass, it hides that method. For example, if the client program creates a Vcr object and calls the calcDeposit() method, it will always execute the Vcr version of calcDeposit(): Vcr v = new Vcr(…); // Create a Vcr object v.calcDeposit(); // Executes Vcr calcDeposit() method Calling an Overridden Method from the Subclass Within the Vcr version of calcDeposit(), we can call the InventoryItem version of calcDeposit() defined in the superclass by using the super keyword. The super keyword is similar to this, except that it acts as a reference to the current object as an instance of its superclass. Calling a hidden superclass method using super helps avoid duplicating the code contained in the hidden method; by reducing the amount of duplicate code, the code is more consistent and easier to maintain. Working in JDeveloper You can take advantage of JDeveloper’s built-in functionality to see all the methods of a given class, plus its inherited methods (taken from the superclass). To do this, select the class (Game, for example, which extends InventoryItem), right-click and select Class Editor), and then click the Methods tab (the third tab from the left). Toggle the “Show Inherited Methods” check box to display methods. The same behavior is available in the Fields tab.
  24. A Subclass Is Plug Compatible with Its Superclass Plug compatible means that any Java subclass object can be assigned to an object reference variable declared as its superclass, or as the same class as itself. The slide example shows a Vcr object is assigned to the item object reference, which is declared as an InventoryItem. The java compiler accepts this as valid syntax, and it is necessary for polymorphism to be possible. There are two ways to look at the code example: The Compiler View The compiler sees the Vcr object as if it is a “kind of” InventoryItem. Therefore, all methods called from the item object reference can only be those defined in the InventoryItem class, because item is defined as an InventoryItem. In essence, you are writing generic code to deal with common functionality of any kind of inventory item object. The Run-Time View At run time the JVM will dynamically create the Vcr object. Thus when you call a method, such as, item.calcDeposit() it is the the Vcr’s calcDepost() method that is invoked if it overrides its superclass definition. Otherwise, the inherited method is called. The JVM uses a run-time type checking mechanism to ensure the call is valid, otherwise it throws an exception. Later in this lesson, you will see that you can determine the object type associated with a reference at run time by using the the instanceof operator.
  25. Acme Video Acme Video started as a simple video rental business that only rented videos. As business began to improve Acme Video decided to branch out and add video games to its inventory. It soon started getting requests for VCRs and for video game devices. Each of the different items we are now renting has unique properties, and we handle each type in a slightly different manner. For example, we require a deposit on the VCRs and video game devices, but not on videos and games. The deposit is based on the type of equipment and the customer. Regular, established customers with good credit are not required to leave a deposit, while new customers are. When the customer checks out, we need to determine the price of the items as well as any required deposit. Our application has to be flexible enough to accept new types of items without having to change or recompile existing code each time we expanded our business. We accomplished this goal by using Java’s polymorphic abilities. We designed the ShoppingBasket class to simply accept and process InventoryItems, whatever type they may be. We then let Java determine the type of the item and call the correct methods based on that type. Using this technique, we can add as many new item types as we need without having to change or recompile existing code.
  26. How It Works When we designed our video rental application, we did not know all the types of InventoryItem that we would rent in the long term. In non-OO programming, this would create a problem that would be solved by modifying code each time a new type was added. In Java, we can use polymorphism to solve the problem. Here’s how: The calcDeposit() method in the InventoryItem class is overridden in the Vcr and Movie classes to provide object-specific calculation logic. The ShoppingBasket class includes an addItem(InventoryItem item) method that calls the calcDeposit() method using an InventoryItem object. At run time, Java interrogates the argument to determine its actual object type and determines if the type has an overriding method. If it does, Java uses the subclass method in place of the superclass method. For example, if movie is a variable of type Movie and Vcr is a variable of type Vcr: addItem(movie);// calls the Movie version of calcDeposit() addItem(vcr);// calls the Vcr version of calcDeposit() The addItem method accepts any kind of InventoryItem object, including the plug-compatible subclass objects. The significance is that the ShoppingBasket or InventoryItem classes do not need to change as new InventoryItem types are added to our business. The OO-designed code will continue to work.
  27. The instanceof Operator The instanceof operator can be used to determine the type of an object at run time. It is useful in situations where you need to call some subclass-specific operation on an object, but need to first verify that the object is the correct type. The syntax of the instanceof operator is as follows: objectRef instanceof className The instanceof operator returns a Boolean value. If the object referred to by objectRef is an instance of the specified className, or one of its subclasses, the instanceof operator returns true. Otherwise, it returns false. Example The method in the slide takes an object reference whose compile-time type is declared as InventoryItem. However, at run time, the object passed into the method might be any kind of InventoryItem, such as Vcr, Movie, or Game. Inside the method, we use instanceof to test whether we have a Vcr object. If so, we convert the compile-time type of the object reference into the Vcr type, and then call a Vcr-specific method. This is often called downcasting. Downcasting The downcast is necessary in this example. Without it, the compiler would only let us call methods defined in the InventoryItem class. Having said that, you should use downcasting sparingly. There are usually alternative designs that obviate the need for excessive downcasting.
  28. final Methods Methods and classes are made final for two primary reasons: security and optimization. If a method is performing some vital operation, such as identity validation or authorization checking, it should be declared final to prevent anyone from overriding the method and circumventing your security checks. Many of the methods defined in java.net classes are final, for example. final Classes If you declare a class as final, it can never be extended by any other class. This is a strong design statement that the class is sufficient to cater for all current and future requirements. The implication is clear: you do not even need to think about inheriting from this class. The Color class in java.awt is declared final, for example. final Classes and final Methods Yield More Efficient Code final classes can help the compiler produce more efficient code. Because a final class cannot be extended, if the compiler encounters an object reference of that type, and you call a method by using that object reference, the compiler does not need to perform run-time method binding to cater for any subclasses that might have overridden the method. Instead, the compiler can perform static binding; that is, the compiler can decide which method to call and avoid the overhead of run-time polymorphic lookup. This is true for individual final methods as well. If you call a final method anywhere in your program, the compiler can call that method statically, without worrying about whether the method might be overridden by some subclass.
  29. Inheritance Represents an “Is a Kind of” Relationship Use inheritance only to model a genuine “is a kind of” relationship. In other words, do not use inheritance unless all of the inherited methods apply to the subclass. If you cannot substitute a subclass object for a superclass object, you do not have a genuine “is a kind of” relationship. In this case, the classes may be related, but not hierarchically. If you do use inheritance, exploit the polymorphic nature of the instance methods in the inheritance hierarchy. For example, if you find that you need to test for the type of an object in an inheritance tree, use polymorphism to avoid having to write separate code to handle objects of each class. This maximizes the reusability of your code and makes your code easier to maintain in the future.
  30. Schedule:TimingTopic 40 minutesLecture 60 minutesLab 110 minutesTotal
  31. Overview In Java, you can define classes that are high-level abstractions of real-world objects. Using these high-level classes gives the designer a vote in what subclasses look like and even which methods are mandatory in the subclass. Abstract Classes An abstract class is simply a class that cannot be instantiated; only its nonabstract subclasses may be instantiated. For example, an InventoryItem does not contain sufficient detail to provide anything meaningful to the business. It must either be a movie or a VCR. An InventoryItem does, however, serve as a collection of data and behaviors that are common to all items that are available for rent. Abstract Methods Abstract methods go a step beyond standard inheritance. An abstract method defined within an abstract class must be implemented by all of its subclasses. This technique allows the class designer to decide exactly what behaviors a subclass must be able to perform. The designer of the abstract class cannot determine how the behaviors will be implemented, only that they will be implemented. Interfaces An interface is the specification of a set of methods, similar to an abstract class. In addition to what an abstract class offers, an interface can effectively provide multiple inheritance. A class can implement an unlimited number of interfaces but can only extend one superclass.
  32. Defining Abstract Classes in Java Java provides the abstract keyword, which indicates that a class is abstract. For example, the InventoryItem class in the slide has been declared as abstract: public abstract class InventoryItem { … } InventoryItem is declared abstract because it does not possess enough intelligence or detail to represent a complete and stand-alone object. The user should not be allowed to create InventoryItem objects, because InventoryItem is only a partial class. The InventoryItem class exists only so that it can be extended by more specialized subclasses, such as Movie and Vcr. What Happens If You Try to Instantiate an Abstract Class? If you try to create a InventoryItem object anywhere in the program, the compiler flags an error: InventoryItem i = new InventoryItem (…);// Compiler error The user can only create objects of the concrete subclasses: Movie m = new Movie(…);// This is fine Vcr v = new Vcr(…);// This is fine too
  33. The Need for Abstract Methods When designing an inheritance hierarchy, there will probably be some operations that all classes perform, each in its own way. For example, in a video rental business, the vendor must know if each item is rentable or not. Each type of item, however, determines if the item is rentable in a specific way. To represent this concept in Java, the common “is this item rentable” method is defined in the InventoryItem class. However, there is no sensible implementation for this method in InventoryItem, because each different kind of item has its own requirements. One approach might be to leave the method empty in the InventoryItem class: public abstract class InventoryItem{ public boolean isRentable(); { return true; } } This approach is not good enough because it does not force each concrete subclass to override the method. For example, in the Vcr class, if the user forgets to override the isRentable() method, what will happen if the user calls the method on a Vcr object? The isRentable()method in InventoryItem will be called and always return true. This is not the desired outcome. The solution is to declare the method as abstract, as shown on the next page.
  34. Defining Abstract Methods in Java To declare a method as abstract in Java, prefix the method name with the abstract keyword as follows: public abstract class InventoryItem { abstract boolean isRentable(); … } When you declare an abstract method, you just provide the signature for the method, which comprises its name, its argument list, and its return type. You do not provide a body for the method. Each concrete subclass must override the method and provide its own body. Now that the method is declared as abstract, all subclasses must provide an implementation of that method. Abstract classes can contain methods that are not declared as abstract. Those methods can be overridden by the subclasses but it is not mandatory.
  35. What Is an Interface? An interface is similar to an abstract class, except that it cannot have any concrete methods or instance variables. It is a collection of abstract method declarations and constants-that is, static final variables. It is like a contract that the subclass must obey. Any class that implements an interface must implement all of the methods specified in that interface. A class can implement many interfaces but can extend only one class. Java does not support inheritance from multiple classes, but it does support implementing multiple interfaces. For example: class Movie extends InventoryItem implements Sortable, Listable { … } As previously demonstrated, Movie inherits all of the attributes and behaviors of InventoryItem. In addition, it now must provide implementation details for all of the methods specified in the Sortable and Listable interfaces. Those methods can be used by other classes to implement specific behaviors like a sort routine. Instructor Note Interface is a way to bypass the multiple inheritance restriction that Java has.
  36. Example of Interfaces Interfaces describe an aspect of behavior that many different classes require. The name of an interface is often an adjective such as Steerable, Traceable, Sortable, and so on. This is in contrast to a class name, which is usually a noun such as movie or customer. The Steerable interface may include such methods as: turnRight(), turnLeft(), turnAround(), and so on. Any class that needs to be steerable may implement the Steerable interface. The classes that implement an interface may be completely unrelated. The only thing they may have in common is the need to be steered. For example, the core Java packages include a number of standard interfaces such as runnable, cloneable, and ActionListener. These interfaces are implemented by all types of classes that have nothing in common except the need to be cloneable, or to implement an ActionListener.
  37. Defining Interfaces in Java You can define an interface using the interface keyword. All methods specified in an interface are implicitly public and abstract. Any variables specified in an interface are implicitly public, static, and final; that is, they are constants. Therefore, the interface definition shown in the slide is equivalent to the following definition, where the public, static, final, and abstract keywords have been specified explicitly. public interface Steerable { public static final int MAXTURN = 45; public abstract void turnLeft(int deg); public abstract void turnRight(int deg); } Because interface methods are implicitly public and abstract, it is a generally accepted practice not to specify those access modifiers. The same is true for variables. Because they are implicitly public, static, and final, in other words constants, you should not specify those modifiers. Instructor Note Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted, but strongly discouraged as a matter of style, to redundantly specify one or all of these modifiers for such fields.
  38. Implementing Interfaces The slide shows an example of a class Yacht, that implements the Steerable interface. Yacht must implement all of the methods in any interfaces it implements; in this case Yacht must implement turnLeft() and turnRight(). A class can implement more than one interface if it wants to, by specifying a list of interfaces separated by commas. Consider the following example: public class Yacht extends Boat implements Steerable, Taxable { … } Here, the Yacht class implements two interfaces: Steerable and Taxable. This means the Yacht class must implement all the methods declared in both Steerable and Taxable.
  39. Sort A sort is a classic example of the use of an interface. Many completely unrelated classes must use a sort. A sort is a well known and well defined process that does not need to be written repeatedly. A sort routine needs to provide the ability to sort any object in the way that fits that particular object. The traditional programming approach would dictate a number of subroutines and an ever growing decision tree to manage each new object type. By using good OO programming technique and interfaces, you can eliminate all of the maintenance difficulties associated with the traditional approach. The Sortable interface specifies the methods required to make the sort work on each type of object that needs to be sorted. Each class implements the interface based on its specific sorting needs. Only the class needs to know its object comparison, or sorting rules. Implementing the sort in the OO way provides a model that supports very good code reuse. The sort code is completely isolated from the objects that implement the sort. Instructor Note Use the sort examples to demo. Open the Demo.jws. There are two projects: Sort and ExtendedSort. Start with the Sort project and launch the SortApplication.java for a simple demo. Use the ExtendedSort project for a more complex demo. Launch the ExtendedSortApplication.java file to demonstrate a double sort application.
  40. Overview of the Classes The slide shows the three classes and one interface involved in sorting a list of videos. The classes are divided into two categories: Classes created by the sort expert, who knows all about sort algorithms but nothing about individual objects that people might want to sort Classes created by the movie expert, who knows all about movies, but nothing about sort algorithms You will see how interfaces can separate these two types of developers, enabling the separation of unrelated areas of functionality. Classes and Interfaces Used by the Example The Sortable interface declares one method: compare(). This method must be implemented by any class that wants to use the sort class methods. The Sort class is an abstract class that contains sortObjects(), a method to sort an array of objects. Most sort algorithms work by comparing pairs of objects. sortObjects() does this comparison by calling the compare() method on the objects in the array. The Movie class implements the Sortable interface. It contains a compare() method that compares two Movie objects. MyApplication represents any application that needs to sort a list of movies. It could be a form displaying a Sortable list of movies.
  41. How the Sort Works The slide shows the process of sorting a list of objects. The steps are as follows: 1.The main application passes an array of movies to Sort.sortObjects(). 2.sortObjects()sorts the array. Whenever sortObjects() needs to compare two movies, it calls the compare() method of one movie, passing it with the other movie as a parameter. 3.The movie returns the results of the comparison to sortObjects(). 4.sortObjects() returns the sorted list. Instructor Note The java.lang.Comparable interface used with Collections.sort(List) from the java.util package provide the developer with ready made sort functionality. The class implementing the Comparable interface only needs to implement a int compareTo(Object o) method, that returns a -1, 0, 1 for a less than, equal to, or greater than result.
  42. The Sortable Interface The Sortable interface specifies all of the methods and constants required for a class to be sortable. In the example, the only method is compare(). Any class that implements Sortable must provide a compare() method that accepts an Object argument and returns an int. The result of the compare method is as follows: Note: It is entirely up to the implementer of compare() to determine the meaning of “greater than,” “less than,” and “equal to.”
  43. The Sort Class The Sort class contains the sortObjects() method, which sorts an array of Sortable objects. sortObjects() accepts an array of Sortable as its argument. It is legal syntax to specify an interface type for a method’s argument; in this case it ensures that the method will be asked to sort only objects that implement the Sortable interface. In the example sortObjects() executes a simple sort that steps through the array several times, and compares each item with the next one and swaps them if necessary. When sortObjects() needs to compare two items in the array, it calls compare() on one of the items, passing the other item as the argument. Note that sortObjects() knows nothing about the type of object it is sorting. It knows only that they are Sortable objects, and therefore it knows that it can call a compare() method on any of the objects, and it knows how to interpret the results. Interface as a Contract You can think of an interface as a contract between the object that uses the interface and the object that implements the interface. In this case, the contract is as follows: The Movie class (the implementer) agrees to implement a method called compare(), with parameters and return value specified by the interface. The Sort class (the user), agrees to sort a list of objects in the correct order..
  44. Implementing the Interface The Movie class implements the Sortable interface. If it wants to call Sort.sortObjects(), it must implement the Sortable interface, and if it implements the Sortable interface, it must implement the compare() method; this is the contract. The compare() method takes an Object as an argument and compares it with the object on which it was called. In this case, we use the String compareTo() method to compare the two title strings. compareTo() returns a positive integer, a negative integer, or zero depending on the relative order of the two objects. When implementing compare(), you can compare the two objects in any way you like, as long you return an integer that indicates their relative sort order. Note: In the example, movie2 is an Object, so it must be cast to Movie before you can call getTitle() to get its title.
  45. Using Sort To use the sort, you simply call Sort.sortObjects(Sortable []) from your application, passing the array of objects you want sorted. Each object that you want to sort must implement the Sortable interface and provide the required compare() method. Only the class implementing Sortable knows exactly how its objects are sorted. You can make other types of objects in your application sortable. For example, you could make the Rental and Member classes implement the Sortable interface and add a compare() method to each class. Then you could sort an array of Rental or Member by calling Sort.sortObjects(). The compare() method in each of the classes can be radically different or fundamentally the same. The only requirement is that the compare() methods return an integer to indicate the relative sort order of the objects.
  46. Instructor Note This lesson reviews the inheritance and polymorphism properties that were introduced in lesson 2, but from a Java language point of view. Schedule:TimingTopic 50 minutesLecture 40 minutesPractice 90 minutesTotal
  47. Inner Class Definition An inner class is simply a class defined within a class. You define inner classes because they functionally support the outer class or because they make sense in the context of the enclosing class. Inner classes have different privileges when accessing outer class members according to the type of inner class they are. There are four different types of inner classes: Defined in a class: Static Inner Class Member Inner Class Defined in a method: Local Inner Class Anonymous Inner class You should be careful when using inner classes, because they can make the code more difficult to read, specially for people having to maintain the application. Inner classes result from the combination of block structure with class-based programming, which was pioneered by the programming language Beta. Using block structure with inner classes makes it easier for the Java programmer to connect objects together, because classes can be defined closer to the objects they need to manipulate, and can directly use the names they need.
  48. Static Inner Classes Static inner classes as the name states it, are defined as static, meaning that they have access only to the static components of the outer class with no access to instance components such as methods and variables. In some specific cases, the inner class may instantiate an instance of the outer class. In that case, the static inner class can access the instance components of the instance it has created. An example of use of a static inner class is to implement an iterator. An iterator provides the necessary behavior to get to each element in a collection without exposing the collection itself. In a class manipulating a collection, it is a good practice to use an iterator implemented as a static inner class to return an iterartor instead of the collection of all the elements. Iterator is an interface defined in the java.util package. Its interface is defined as follows: public interface Iterator {public boolean hasNext();public Object next();public void remove();} Static inner classes are compiled to separate class files. In this case the Outer$InnerStatic.class file is created.
  49. Member Inner Classes Member inner classes are defined within the scope of an enclosing class omitting the static keyword. Member inner classes can access all the components, static and instance methods and variables, of the outer class, simply because they can exist only in the context of an instance of the outer class. An instance of the outer class needs to exist to be able to create a new instance of the member inner class. public class Outer { public class InnerMember { public void innerMethod() { // ‘this’ refers to an instance of Outer.InnerMember // ‘Outer.this’ refers to an instance of Outer // ‘super’ refers to the superclass of InnerMember (Object) // ‘Outer.super’ refers to the superclass of Outer } }} Member inner classes are compiled to separate class files. In this case the Outer$InnerMember.class file is created.
  50. Local Inner Classes Local inner classes are declared within the code block of a method. The code location can be anywhere within the method. In order to have access to the variables of the outerMethod, they need to be declared as final. Local inner classes cannot be declared public, protected, private, or static and cannot have static members. Their use is very limited, because most problems can be solved with the other types of inner classes. Are defined at method level Are declared within a code block Have access only to final variables Cannot have a constructor All static and instance variables of the enclosing class are accessible if the local class is defined within an instance method. Only static variables of the enclosing class are accessible if the local class is defined with a static method.
  51. Anonymous Inner Classes Anonymous inner classes are local inner classes with no class name. The class keyword is omitted and so are public, protected, extends, and implements. They are commonly used to implement user interface adapters to perform event handling when using AWT or Swing events. This topic is covered later in the course. Anonymous inner classes have the same restriction as local inner classes concerning the visibility on the outer class elements. The generic anonymous class syntax takes the form: Class Outer { … AnInnerAnonymousClass (new SuperClass ( ) { . . . } ); . . . } The anonymous class is derived from a superclass that allows the use of the methods of this superclass. Anonymous inner classes can implicitly extend or implement only other classes or interfaces. The use of anonymous classes is most effective when they implement only a single or very few small methods. Reading the code can get confusing when the definition of the inner class is long. Anonymous Inner classes have the same accessibility rules as the previous page because it is a local class. It is primarily used to create a one-time implementation class of an interface.
  52. Using instanceof with Interfaces In the lesson on inheritance, you should have learned how to use the instanceof operator to test whether the run-time type of an object matched a certain type. You can also use instanceof with interfaces, as shown by the method in the slide. The method takes an argument whose compile-time type is Object. At run time, the argument can be any kind of object inherited from Object. The instanceof operator tests the object to see whether it is an instanceof Sortable. In other words, does the object support the Sortable interface? This means that you do not care what kind of object you are dealing with. Your concern is whether the object is capable of having the compare() method called upon it. If the object does implement the Sortable interface, you cast the object reference into Sortable so that the compiler will let you call the compare() method.