Title: Interfaces, Inhteritance, Polymorphism
1Lesson 3
- Interfaces, Inhteritance, Polymorphism
2What is an Java interface?
- Like a class but only contains abstract methods
and final variables - example
- interface FooInterface
- void foo1()
- int foo2(double x)
-
- abstract interface FooInterface
- public abstract void foo1()
- public abstract int foo2(double x)
-
Both are correct! the abstract and
public keywords are implied, so the shorthand is
recommended.
3Interfaces, cont.
- Unlike a class, an interface cannot be
instantiated! - Rather, an interface is implemented by some other
class - class FooClass implements FooInterface
- ....
-
- This means one thing only FooClass must contain
versions of both foo1 and foo2 that actually do
something useful. We say that FooClass must
provide implementations for all of the methods in
FooInterface.
4Interfaces, cont.
- When a class implements an interface, think of
the class as entering a contract to provide meat
for all methods in the interface. - The compiler will check that this contract is
adhered to. - Otherwise, the class implementing the interface
can contain anything else that a regular class
contains. - Again do not try to instantiate an interface
this is meaningless!
5More interface rules
- A class may implement any number of interfaces
as - class FooClass implements A, B, C
- ...
-
- An interface may also contain public static final
variables. Usually, these qualifiers are left
off. We just say - interface MyConstants
- double PI 3.141592
- double E 1.7182818
-
can be acessed as either MyConstants.PI or just
PI by any class that implements the interface
6Certification-type questions
- What happens when multiple interface
implementation results in name conflicts? - if the methods have different signatures, they
are considered overloaded and there is no problem - if the methods have the same signature and the
same return type, they are considered to be the
same method. - if they have the same signature and different
return types, a compilation error will result. - If they have same signature/return type but throw
different exceptions, they are considered to be
same, and resulting throws list is union of
original two
7Marker Interfaces
- Some interfaces contain no methods or constants
at all (ie they are empty). - These are called marker interfaces.
- Examples are Cloneable and Serializable in java
library. - We will understand these better once we
understand subtype-supertype relationships.
8Subtyping with Interfaces
- Understanding mechanics of interfaces is only
about 1/3 of the story. - Next, we have to understand how interfaces allow
for polymorphism. - Finally, we study probably the hardest part how
to best use polymorphism to really write superior
code.
9Rules of subtyping
- If class C implements interface I, then C is a
subtype of I. - What does this imply? We can do things like
- C aC
- aC new C()
- I aC
- aC new C()
- In the latter case, we often say that the runtime
type of aC is C, but the static or declared type
is I. - In the former case, both types are C
This is the regular stuff
Can do this also!
10Substitutability of Types
- Rule A value of a subtype can appear wherever a
value of its supertype is expected. In other
words, a value of a sybtype can always substitute
for a value of a supertype. - To rephrase for objects An instance of a
subclass can appear wherever an instance of a
superclass is expected. - Note superclass here refers to interface at this
point. We will make more general soon.
11Generic examples of subtyping
class Circle implements Drawable, Scalable
... Circle aCircle Drawable aDrawable Scalable
aScalable aCircle new Circle() //ok aCircle
new aDrawable() //BAD! aDrawable new
Circle()//ok aScalable new Circle()
//ok 1,3,4 are ok because a Circle object is
created and it is assigned to a declared type of
either Circle or one of its supertypes.
12More examples
Drawable aDrawable Circle aCircle aCircle new
Circle()//fine aDrawable aCircle//fine
aDrawable is type superclass aDrawable new
Circle() aCircle aDrawable //NO cannot
assign more general to
//more specific without an explicit
//cast aCircle
(Circle) aDrawable //this is ok explicit
cast!
13Widening and Narrowing
- The conversion of a subtype to one of its
supertypes is called widening. The conversioning
of a supertype to one of its subtypes is called
narrowing. - Widening happens automatically during an
assignment. Nothing special is required. This is
also typically called upcasting. - Narrowing requires a proper explicit cast,
otherwise the compiler will complain. This is an
example of Javas very strong typing. It is your
best friend. Narrowing is also known as
downcasting.
14ClassCasts and instanceof
- The java compiler will allow any cast. If the
cast is illegal, a runtime exception will be
thrown (ClassCastException). - There are two ways to safeguard against this.
- with a try-catch block (later)
- Using the instanceof operator as
- if (aDrawable instanceof Circle)
- aCircle (Circle) aDrawable
-
- instanceof tells the actual type of an object
rather than its declared type.
15Why on earth do this?
- How could this ever be used to your advantage?
Why not simlply type all Circles as Circle, etc.
In other words, why ever do - Drawable aCircle new Circle()
- vs.
- Circle aCircle new Circle()
- Much easier to understand if we use upcasting in
method calls.
16Using Upcasting in method calls
Imagine there is a class Renderer that has a
method Render that can operate on any object that
knows how to morph any two objects that can draw
themselves. e.g. class Renderer ...
public void morph(Drawable o1, Drawable o2)
// calls made to o1.draw(), o2.draw() here\
You can call morph as e.g. Renderer rn new
Renderer() Circle c new Circle() Rectangle r
new Rectangle() rn.morph(c,r) //c,r are
automatically upcast to Drawables
17Comparable interface
- Another good example is Javas Comparable
interface, which contains the compareTo method. - One of the Arrays.sort methods operates on any
array of Objects that implement the Comparable
interface. - Thus, specific objects to be sorted are
implicitly upcast when passed to the sort method.
18When is downcasting needed?
- Once an object is upcast, you cannot call methods
that do not exist in the supertype. - For example, if Rectangle objects have a method
called rotate(), that method cannot be called
from within morph unless an explicit downcast is
performed. - This is an example of Javas strong typing. The
compiler cannot be sure that the actual object
passed in has a rotate method, so it forces you
to say so explicitly.
19Extending interfaces
- An interface may also extend another interface.
- In that case, the extender is known as the
superinterface and the extendee is the
subinterface. - Example
- interface FooInterface
- int foo1()
-
- interface FooInterface2 extends
FooInterface - int foo2()
-
- FooInerface2 contains both methods foo1 and foo2,
and anything that implements - FooInterface2 must implement both of these.
20Part III How interfaces are used
- This is difficult because there is no single,
simple answer to the question. - Like any semantic feature in a programming
language, there are no hard and fast rules about
in what situations it should best be exploited. - However, there are many guidelines and general
strategies (or else the feature would have never
bee included). - Well cover a few ways in which interfaces are
typically used.
21Some interface uses
- To simply clarify the the functionality
associated with a particular abstraction. - To abstract functionality in a method to make it
more general, such as pointers to functions are
used in C. sort is a good example. - To implement callbacks, such as in GUI
programming - To write more general, implementation depending
code that is easy to extend and maintain. - To simulate global constants.
22Clarifying functionality
- Often you just want to write a code to do
something. It will never do anything else. You
are not concerned about extensibility. - Even in such a case, it can be nice to organize
your program using interfaces. It makes the code
easy to read and the intent of the author very
clear.
23Callbacks
- Callbacks are a general programming technique
where a method call another method which then
calls the calling method (typically to inform the
caller when some action has taken place). - Timer and Swing ActionListeners are good examples.
24To write more general implementation
- A method that operates on a variable of type
interface automatically works for any sub-type of
that interface. - This is much more general than writing your
program to operate only on a particular subtype. - See Shape example.
25Abstracting functionality
- A method can often be made more general by
customizing its work based on the implementation
of some other function that it calls. - sort(...) is a good example. A sort() function
can sort any list of items as long as you tell it
how to compare any two items. - Numerical methods for solvering differential
equations often depend on taking discrete
derivatives you can make such a routine general
by specifying the derivate technique
independently.
26Ineritance
27Basic inheritance
- Interfaces can be thought of as a special case of
a more general class relationship called
inheritance. - When a class C2 inherits from or extends another
class C1, C1 is called the superclass of C2, and
C2 the subclass of C1. - This means that all of the public and protected
members of the superclass are available to the
subclass. This includes implementation and
instance variables! - Any class that is not explicitly declared as
final can be extended.
28Inheritance syntax
For one class to be a subclass of another, we
use the extends keyword class GradStudent
extends Student ... class Manager extends
Employee... etc. The superclass requires no
special syntax.
29Subtyping
- Everything we learned about typing and subtyping
holds a fortiori for super and subclasses. - Specifically, classes which extend other classes
are of both type superclass and type subclass. - A class can only extend a single class (no
multiple implementation inheritance).
30Method overriding
- Overriding refers to the introduction of an
instance method in a subclass that has the same
name, signature, and return type of a method in
the superclass. - Implementation of this method in the subclass
replaced the implementation of the method in the
superclass.
31Overriding example
class A public void m1()... class B
extends A public void m1()... For objects
of class B, its own unique version of m1 will
be called. We say that the method m1 in B
overrides the method m1 in its superclass.
32Enough for now