Lecture 6: Interfaces, Polymorphism,
Inheritance
What You Will Learn Today
- Compare programming paradigms.
- Create and use interfaces.
- Use polymorphism.
- Use inheritance to create and use subclasses.
- Use method overloading and overriding.
- Use abstract classes and methods, final classes
and methods, and nested and
inner classes.
Approaches to programming have developed over time roughly in this order:
- monolithic program: one long main method, global variables,
unstructured branching
- procedural program: procedures with parameters and return value;
local variables
- modular program: set of procedures with data they manipulate; data
is hidden in the module
- abstract data types: user-defined types used in addition to
built-in types
- object-based program: classes of objects which group methods and
attributes
- object-oriented program: objects belong to a hierarchy of classes
which share properties through inheritance
- generic program: a group of algorithms that work for a variety of
data structures
Why are these new approaches necessary?
- An interface declares a set of methods and their formats.
- The methods are
public
and abstract
. They do not
have implementations (body).
public interface InterfaceName
{
returnType methodName(parameters);
}
public interface Measurable
{
double getMeasure();
}
- A class that implements interfaces must provide the methods of the
interfaces.
public class ClassName implements InterfaceName1,
InterfaceName2, ...
{
accessType returnType methodName(parameters) {
implementation } ...
}
public class BankAccount implements Measurable
{
public double getMeasure() { return balance; }
}
Using Interfaces
- An interface helps to be able to call a method of several different
objects without worrying about the object type.
- Many types of objects can be measured in some way: bank accounts,
shapes, people
- Shape interface could provide area() and volume() methods for
classes Sphere and Cylinder.
- An interface can be used to declare an object reference variable (that
later points to an object).
- You can convert to a class type to an interface type if the class realizes
the interface.
-
BankAccount account = new BankAccount(); Measurable x =
account;
- To convert from an interface type to a class type you must use a cast.
-
Measurable x = BankAccount account = (BankAccount) x;
- The
instanceOf
operator tests if an object belongs to
a type.
-
if (x instanceOf BankAccount) ...
- Interfaces cannot have changing variables, but interfaces can use constants.
- Interface variables are automatically
public static final
but
do not declare them as such.
- Interface names often end in -able, -or or -er. The Java standard library includes interfaces such as:
Comparable
compares objects.
Iterator
moves through a group of objects (for
processing them).
ActionListener
"listens" for user interface events
(e.g. from keyboard, mouse) and performs assigned actions.
- What are the similarities and differences between interfaces and classes?
- Polymorphism means "many shapes" or "many forms".
- A polymorphic method reference can refer to different types of
objects at different times.
- Method behaviour differs depending on object type.
- Find the area
of or draw a square, rectangle, parallelogram, trapezoid, circle, ellipse,
triangle, etc.
- Polymorphism makes systems extensible and maintainable.
- It is easy to add new types of objects without changing the code
that deals with those objects.
- Every type of Shape knows how to position itself, move itself, draw
itself, etc.
- The main program simply directs all shapes to position, move, and draw
themselves.
- There is no need for a
switch
statement that chooses a
method depending on object type.
- Late binding or dynamic binding is a reference
determined only when used, at run time (by the virtual machine).
- e.g. a polymorphic reference
- Early binding is when the compiler selects a method.
- method
overloading: two methods with different parameters
substring(int begin)
and substring(int begin, int end)
- What is the difference between overloading and polymorphism?
- Inheritance is when a class can use attributes and methods of
another class.
- A subclass extends a superclass.
-
class
SubClassName extends
SuperClassName
- The subclass increases the functionality of the superclass by adding
instance variables and methods.
- The subclass is larger and more complex than the superclass.
- A subclass is more
specific than its superclass and represents fewer objects.
- Vehicle ← Car, Truck, Van, Bus, Tank,
Bicycle, Motorcycle
- Account ← CheckingAccount,
SavingsAccount
- A superclass and subclass have an "is a" relationship.
- A Car is a Vehicle; a CheckingAccount is an Account.
- For a "has a" relationship (composition), put the object
inside as an instance variable instead.
- A circle has a center point so it should be accessed as
circle.center.
- When designing a group of classes, determine the common/shared attributes
and behaviours put them in a superclass.
- All bank accounts have an account number, owner and balance, and can
accept deposits and withdrawals.
- Inheritance encourages software reuse and saves development and
maintenance time.
- Most software extends pre-existing objects in libraries and packages.
Inheritance Hierarchy
- A subclass inherits from its superclass and all of its
ancestors.
- Organism ← Animal
← Mammal ←
Primate ← Human
- Person ← Employee, Customer,
UniversityMember
- Employee ← Manager, Engineer,
Assistant, HourlyWorker
- UniversityMember ← FacultyMember,
StaffMember, Student, Alumnus
- Shape ← Shape2D, Shape3D
- Shape2D ← Circle, Triangle, Rectangle
- Classes are arranged hierarchically (form a tree).
- The
Object
class (defined in java.lang) is the root
class (ancestor of all other classes).
- If you do not use the
extends
keyword, your class will extend
Object
.
- Unlike C++, Java does not support "multiple inheritance".
- Unlike a person, a "child" class inherits from only one "parent",
one "grandparent", etc.
- A FacultyMember cannot be both an Employee and UniversityMember in the
class hierarchy above.
- Instead, a class can implement multiple interfaces.
- Hierarchies are useful for managing complexity ("divide and
conquer").
- Most hierarchies only have a few levels. The deepest class in the Java API
tree is 7 levels below
Object
.
- Too many subclasses are difficult to maintain; too few subclasses put too
many features in one class.
- What is the best hierarchy for organizing things?
Using Inheritance
- Objects can always be treated as instances of a superclass.
- To become instances of a subclass, objects must be casted.
Circle circle2 = (Circle) shape1;
// Circle circle2 = shape1;
is a syntax error
this
is the current object.
this
is used to access attributes and methods of the
class being implemented.
- A SavingsAccount method could call its own
toString()
method
using this.toString()
- Use
this
when there is a local variable of the same name,
e.g. in a constructor
public class Circle { Circle (int radius) { this.radius =
radius; ... } ... private int radius; }
super
is the parent object.
super
is used to access attributes and methods of the superclass.
- A SavingsAccount method could call Account's
toString()
method using super.toString()
super.super.x
is a syntax error.
- Unqualified variable and method references (no
this
or
super
) refer to the current object.
- Calling
toString()
from a SavingsAccount method is the same
as calling this.toString()
- Constructors are not inherited by subclasses.
- The subclass constructor should start with a call to the superclass
constructor.
public class Circle extends Shape { public Circle(int x, int y) {
super(x, y); } ... }
- Otherwise, the subclass constructor will call the superclass default
constructor.
- Often a subclass method first calls the superclass method, then does other
work.
- A subclass method cannot have the same parameters but different return
type from a superclass method.
- If
shape.area()
returns an int
,
circle.area()
cannot return a double
.
private
methods and fields are not inherited by
subclasses.
protected
members are accessed by methods of self,
subclasses, and other classes in the same package.
- A subclass cannot directly access private members of
its superclass.
- If the Account balance is private variable, a SavingsAccount method
accessing
super.balance
will give a compile error.
- A method defined in a subclass overrides (redefines) the superclass method with
the same name.
- To access the superclass method from within the subclass, you must then use
super.methodName();
- The
Object
class has three methods that you should consider
overriding in your objects:
toString()
: return a string representation of the
object (e.g. print the object's attributes)
equals(Object obj)
: test if some other object equals
this object
clone()
: create and return a copy of the object
- An abstract class is a class which can only be used through its
subclasses that implement its methods.
- An abstract class uses the keyword
abstract
before the
keyword
class
in the class definition.
- An abstract method must be overridden in a subclass in order to be
used.
- An abstract method uses the keyword
abstract
. Methods of an abstract class are also
abstract.
- A class with an abstract parent must override all abstract methods or it
will also be abstract.
- Use an interface instead of an abstract class when there is no
default implementation to inherit.
- A final class cannot have subclasses.
- A final class uses the keyword
final
.
- A final method cannot be overridden in subclasses.
- A final method uses the keyword
final
. All methods of a final class are also final.
- Small, simple final methods are inlined (replaced by their
definitions by the compiler).
- Inlining removes the overhead of method calls so the program will run more
efficiently.
- A nested class is a class within another class.
- It is within the scope of the class which contains it.
- An inner class is a nested class which is not static.
- It can access instance variables and methods of an object which contains
it.
- How is an inner class different from an object which is an instance
variable of a class?
To Do After Class
-
Readings: Big Java Ch. 9, 11; Lewis & Loftus ch. 5.2-5.4, 7; Deitel & Deitel Ch.
7; Tutorial: Language, Classes and Inheritance
-
Look at the Big Java example of inheritance in the
account/ directory.
-
Project 1 Design Documentation is due Friday.
Homework 3 and
Lab 5 are due next Friday.