You are on page 1of 68

Inheritance and Polymorphism

Object-Oriented
Programming in
Java
Contents
1. Inheritance in Java
Inheriting Classes
The super Reference
Overriding Methods
Polymorphism
The instanceof Operator
final Methods and Classes
2
Contents (2)
1. Abstract Classes
Abstract Methods
2. Interfaces
Defining Interfaces
Implementing Interfaces
3. Using Interfaces (Demo)
3
Access Modifiers
public, private, protected, default
(package)

Access Modifiers
The most common modifiers are the access
modifiers:
public
private
protected
(default)
Access modifiers control which classes
may use a member
5
Access Modifiers Rules
The variables that you declare and use
within a classs methods may not have
access modifiers
The only access modifier permitted to non-
inner classes is public
A member may have at most one access
modifier
6
public
The most generous access modifier is
public
A public class, variable, or method may be
used in any Java program without
restriction
Any public method may be overridden by
any subclass
7
private
The least generous access modifier is
private
Top-level (that is, not inner) classes may
not be declared private
A private variable or method may be used
only by an instance of the class that
declares the variable or method
8
protected
Only variables and methods may be
declared protected
A protected member of a class is
available to all classes in the same
package, just like a default member
A protected member of a class can be
available in certain limited ways to all
subclasses of the class that owns the
protected member. It is visible in
subclasses in different packages too.
9
(default)
Default is the name of the access of
classes, variables, and methods if you
dont specify an access modifier
A classs data and methods may be default,
as well as the class itself
A classs default members are accessible to
any class in the same package as the class
in question
A default method may be overridden by any
subclass that is in the same package as the
superclass
10
Applying Encapsulation in
Java
Instance variables should be
declared as private
Only instance methods can
access private instance
variables
Movie mov1 = new Movie();
String rating = mov1.getRating();
String r = mov1.rating; // Error: private
...
if (rating.equals("G"))
var
aMethod
aMethod()
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 a
Package
Include the package keyword followed by
one or more names separated by dots at the
top of the Java source file




If omitted the compiler places the class in
the default unnamed package
14
package utils;

public class MathUtils {
...
}
Grouping Classes in a
Package
To run a main() method in a packaged class
requires:
The CLASSPATH to contain the directory
having the root name of the package tree
The class name must be qualified by its
package name
15
java cp . myPackage.MainClass
The CLASSPATH with
Packages
Includes the directory containing the top level
of the package tree
16
C:\>set
CLASSPATH=E:\Curriculum\courses\java\practices\les06
Package name
.class location
CLASSPATH
Importing Packages
To use a class defined in other package
(not in current) you should do either:
Import the class or all classes in the
package:


Use the full name of the class:
17
import utils.MathUtils;
...
int sq = MathUtils.FastCalculateSqrt(12345);
int sq = utils.MathUtils.FastCalculateSqrt(12345);
Inheritance and
Polymorphism
Code Reuse Techniques

Key Object-Oriented
Components
Inheritance
Constructors referenced by subclass
Polymorphism
Inheritance is an OO fundamental
InventoryItem
Movie Game Book
Superclass
Subclasses
Example of Inheritance
The InventoryItem class defines methods
and variables



Movie extends InventoryItem and can:
Add new variables
Add new methods
Override methods in InventoryItem class
InventoryItem
Movie
Specifying Inheritance in
Java
Inheritance is achieved by specifying which
superclass the subclass extends





Movie inherits all the variables and methods
of InventoryItem
public class InventoryItem {

}
public class Movie extends InventoryItem {

}
What Does a Subclass
Object Look Like?
A subclass inherits all the instance
variables of its superclass
Movie
title
length
price
condition
public class
Movie extends InventoryItem {
private String title;
private int length;
}
public class InventoryItem {
private float price;
private String condition;
}
Default Initialization
What happens when a
subclass object is created?

If no constructors are defined:
First, the default
parameterless constructor is
called in the superclass
Then, the default
parameterless constructor is
called in the subclass
Movie movie1 = new Movie();
Movie
title
length
price
condition
The super Reference
Refers to the base class
Is useful for calling base class
constructors
Must be the first line in the derived class
constructor
Can be used to call any base class
methods
public class Movie extends InventoryItem {
public Movie() {
super("Matrix 8");
}
}
The super Reference
Example
public class InventoryItem {
InventoryItem(String cond) {
System.out.println("InventoryItem");

}
}
class Movie extends InventoryItem {
Movie(String title) {
super(title);

System.out.println("Movie");
}
}
Base class
constructor
Calls base
class
constructor
Using Superclass
Constructors
Use super() to call a superclass
constructor:
public class InventoryItem {
InventoryItem(float p, String cond) {
price = p;
condition = cond;
}
public class Movie extends InventoryItem
{
Movie(String t, float p, String cond) {
super(p, cond);
title = t;
}
Specifying Additional
Methods
The superclass defines methods for all
types of InventoryItem
The subclass can specify additional
methods that are specific to Movie
public class InventoryItem {
public float calcDeposit()
public String calcDateDue()

public class Movie extends InventoryItem {
public void getTitle()
public String getLength()
Overriding Superclass
Methods
A subclass inherits all the methods of its
superclass
The subclass can override a method with its
own specialized version
Must have the same signature and semantics
as the superclass method
In Java all methods are virtual (unless
declared as final)
This forces the late binding mechanism on
each method call
Overriding Superclass
Methods Example
public class InventoryItem {

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

public float calcDeposit(int custId) {
if (specialCustomer(custId) {
return itemDeposit / 2;
} else {
return itemDeposit;
}
}
}
Invoking Superclass
Methods
If a subclass overrides a method, it can still
call the original superclass method
Use super.method() to call a superclass
method from the subclass
public class InventoryItem {
public float calcDeposit(int custId) {
if
return 33.00;
}
public class Movie extends InventoryItem {
public float calcDeposit(int custId) {
itemDeposit = super.calcDeposit(custId);
return (itemDeposit + vcrDeposit);
}
Treating a Subclass as Its
Superclass
A Java object instance of a subclass is plug
compatible with its superclass definition
You can assign a subclass object to a
reference declared with the superclass:



The compiler treats the object via its
reference, that is, in terms of its superclass
definition
The JVM creates a subclass object, executing
subclass methods, if overridden
31
public static void main(String[] args) {
InventoryItem item = new Movie();
double deposit = item.calcDeposit();
}
Acme Video and
Polymorphism
Acme Video started renting only videos
Acme Video added games and VCRs
Whats next?
Polymorphism solves the problem
ShoppingBasket
void addItem(InventoryItem item) {
// this method is called each time
// the clerk scans in a new item
float deposit = item.calcDeposit();

}
InventoryItem
VCR Movie
calcDeposit(){}
calcDeposit(){} calcDeposit(){}
How It Works
Using the instanceof
Operator
The true type of an object can be
determined by using an instanceof
operator
An object reference can be downcast to the
correct type, if needed
public void aMethod(InventoryItem i) {

if (i instanceof Movie)
((Movie)i).playTestTape();
}
Limiting Methods and
Classes with final
A method can be marked as final to prevent
it from being overridden



A whole class can be marked as final to
prevent it from being extended
public final class Color {

}
public final boolean checkPassword(String p) {

}
When to Use Inheritance?
Inheritance should be used only for is a
kind of relationships:
It must always be possible to substitute a
subclass object for a superclass object
All methods in the superclass should make
sense in the subclass
Inheritance for short-term convenience
leads to problems in the future
Abstract Classes and
Interfaces
Defining Abstract Classes
Abstract classes model abstract
concepts from the real world
Cannot be instantiated directly
Should be subclasses to be instantiated
Abstract methods must be implemented
by subclasses
Abstract
superclass
Concrete
subclasses
InventoryItem
Movie VCR
Creating Abstract Classes
in Java
Use the abstract keyword to declare a
class as abstract
public abstract class InventoryItem {
private float price;
public boolean isRentable()
}
public class Movie
extends InventoryItem {
private String title;
public int getLength()
public class Vcr
extends InventoryItem {
private int serialNbr;
public void setTimer()
What Are Abstract
Methods?
An abstract method:
Is an implementation placeholder
Is part of an abstract class
Must be overridden by a concrete subclass
Each concrete subclass can implement the
method differently
Defining Abstract Methods
in Java
Use the abstract keyword to declare a method
as abstract:
Provide the method signature only
The class must also be abstract
Why is this useful?
Declare the structure of a class without
providing complete implementation of every
method
public abstract class InventoryItem {
public abstract boolean isRentable();

Defining and Using
Interfaces
An interface is like a fully abstract class:
All of its methods are abstract
All variables are public static final
An interface lists a set of method signatures,
without any code details
A class that implements the interface must
provide code details for all the methods of
the interface
A class can implement many interfaces but
can extend only one class
Example of Interfaces
Interfaces describe an aspect of behavior
that different classes require
For example, classes that can be steered
support the steerable interface
Classes can be unrelated
Steerable Nonsteerable
Creating an Interface
Use interface keyword




All methods public abstract
All variables public static final
public interface Steerable {
int MAXTURN_DEGREES = 45;
void turnLeft(int deg);
void turnRight(int deg);
}
Implementing an Interface
Use implements keyword
public class Yacht extends Boat
implements Steerable
public void turnLeft(int deg) {}
public void turnRight(int deg) {}
}
Sort: A Real-World Example
Is used by a number of unrelated classes
Contains a known set of methods
Is needed to sort any type of objects
Uses comparison rules known only to the
sortable object
Supports good code reuse
Overview of the Classes
Created by the sort expert:


Created by the movie expert:
public class
MovieSortApplication
public class Movie
implements Sortable
public interface
Sortable
public class
Sort
MyApplication passes
an array of movies to
Sort.sortObjects()
1
2
3
sortObjects() asks a
movie to compare itself
with another movie
The movie returns
the result of the
comparison
4
sortObjects()
returns the
sorted list
Sort
Movie
MyApplication
How the Sort Works?
The Sortable
Interface
Specifies the compare() method
public interface Sortable {
// compare(): Compare this object
// to another object
// Returns:
// 0 if this object is equal to obj2
// a value < 0 if this object < obj2
// a value > 0 if this object > obj2
int compare(Object obj2);
}
The Sort Class
Implements sorting functionality: the
method sortObjects()
public class Sort {
public static void sortObjects(Sortable[] items) {
// Perform "Bubble sort" algorithm
for (int i = 1; i < items.length; i++) {
for (int j = 0; j < items.length-1; j++) {
if (items[j].compare(items[j+1]) > 0) {
Sortable tempItem = items[j+1];
items[j+1] = items[j];
items[j] = tempItem;
}
}
}
}
}
public class Movie extends InventoryItem
implements Sortable {

private String title;

public int compare(Object movie2) {
String title1 = this.title;
String title2 = ((Movie)movie2).getTitle();
return(title1.compareTo(title2));
}
}
Implements Sortable
The Movie Class
Using the Sort
Call Sort.sortObjects(Sortable [])
with an array of Movie as the argument
public class MovieSortApplication {

Movie[] movieList;

public static void main(String[] args) {

// Build the array of Movie objects

Sort.sortObjects(movieList);
}
}
Sorting with Interfaces
Live Demo

Inner Classes
What Are Inner Classes?
Inner classes are classes defined within a
class
Enforce a relationship between two classes
Are of four types:
Static
Member
Local
Anonymous
public class Outer {
class Inner {
}
}
Defining Static Inner
Classes
public class Outer {

private static float varFloat = 3.50f;
private String varString;

static class InnerStatic {

}

}
Defined at class level
Can access only static members of the outer
class
Defining Member Inner
Classes
public class Outer {

private static float varFloat = 3.50f;
private String varString;
...
class InnerMember {
...
Outer.this
...
}
}
Defined at class level
Instance of the outer is needed
Keyword this used to access the outer instance
Defining Local Inner
Classes
Are defined at the method level
Are declared within a code block
Have access only to final variables
Cannot have a constructor
public class Outer {
...
public void outerMethod(final int var1){
final int var2=5; ...
class InnerLocal {
private int localVar = var1 + var2; ...
}
}
}
Defining Anonymous Inner
Classes
Defined at method level
Declared within a code block
Missing the class, extends, and
implements keywords
Cannot have a constructor
public class Outer {
public void outerMethod(){
myObject.myAnonymous(new SomeClass(){
...
} )
}
}
Using instanceof with
Interfaces
Use the instanceof operator to check if
an object implements an interface
Use downcasting to call methods defined
in the interface
public void aMethod(Object obj) {

if (obj instanceof Sortable) {
result = ((Sortable)obj).compare(obj2);

}
}
Class Diagrams
UML is a standard graphical notation
(language) for software modeling
Class diagrams are standard UML notation for
representing classes and their relationships
Classes are represented by rectangles
containing their members
Relationships are represented by arrows
Several types of relations: associations,
aggregations, compositions, dependencies
Class diagrams visualize the class hierarchies
obtained by inheriting classes and interfaces
61
Class Diagrams Example
62
Shape
#mPosition:Point
struct
Point
+mX:int
+mY:int
+Point
interface
ISurfaceCalculatable
+CalculateSurface:int
Rectangle
-mWidth:int
-mHeight:int
+Rectangle
+CalculateSurface:int
Square
-mSize:int
+Square
+CalculateSurface:int
FilledSquare
-mColor:Color
+FilledSquare
struct
Color
+mRedValue:byte
+mGreenValue:byte
+mBlueValue:byte
+Color
FilledRectangle
-mColor:Color
+FilledRectangle
Questions?
Inheritance and Polymorphism
Problems
1. Create an interface IAnimal that represents
an animal from the real world. Define the
method talk() that prints on the console the
specific scream of the animal ("jaff" for dogs,
"muaw" for cats, etc.). Add a boolean method
coultEat(IAnimal) that returns if given
animal eats any other animal.
2. Create classes Dog and Frog that implement
IAnimal interface. Use instanceof operator
in the method couldEat(IAnimal).
3. Create an abstract class Cat that partially
implements the interface IAnimal.
64
Problems
1. Inherit from the base abstract class Cat and
create subclasses Kitten and Tomcat. These
classes should fully implement the IAnimal
interface and define an implementation for the
abstract methods from the class Cat.
2. Write a class TestAnimals that creates an
array of animals (IAnimal[]): Dog, Frog,
Kitten, Tomcat and calls their methods
through IAnimal interface to ensure the
classes are implemented correctly.
65
Homework
1. Create a class diagram for the hierarchy
IAnimal, Dog, Frog, Cat, Kitten, Tomcat.

66
Problems
1. Create a project, modeling a restaurant
system. You need to model the Restaurant,
People (Personnel and Clients), Orders from a
client and Products for orders. Products could
be Meals or Beverages.
2. Client has one order and could buy many
products. Orders are limited to a maximum
bill. No products could be added above the
maximum.
3. Clients could pay with tip included (bill = price
+ tip)
67
Problems
1. Tasks:
Model the scheme and conventions
Find the top 5 clients with largest bills
Sort clients by name in a collection
Design a function to find the day revenue of
the restaurant
Find the waiter with most tips
68

You might also like