Interfaces, Inhteritance, Polymorphism - PowerPoint PPT Presentation

1 / 53
About This Presentation
Title:

Interfaces, Inhteritance, Polymorphism

Description:

... to be sorted are implicitly upcast when passed to the sort method. ... Once an object is upcast, you cannot call methods that do not exist in the supertype. ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 54
Provided by: peopleCs
Category:

less

Transcript and Presenter's Notes

Title: Interfaces, Inhteritance, Polymorphism


1
Interfaces, Inhteritance, Polymorphism
2
What 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.
3
Interfaces, 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.

4
Interfaces, 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!

5
More 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
6
Certification-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

7
Marker 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.

8
Subtyping 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.

9
Rules 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!
10
Substitutability 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.

11
Generic examples of subtyping
class Circle implements Drawable, Scalable
... Circle aCircle Drawable aDrawable Scalable
aScalable aCircle new Circle() //ok aCircle
new Drawable() //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.
12
More 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!
13
Widening 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.

14
ClassCasts 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.

15
Why 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.

16
Using 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
17
Comparable 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.

18
When 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.

19
Extending 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.

20
Part 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.

21
Some 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.

22
Clarifying 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.

23
Callbacks
  • 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.

24
To 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.

25
Abstracting 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.

26
Ineritance
27
Basic 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.

28
Inheritance 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.
29
Subtyping
  • 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).

30
Method 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.

31
Overriding 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.
32
What is the point?
  • Great advantage of implementation inheritance is
    code re-use.
  • By factoring functionality common among many
    classes to a single superclass, each subclass is
    much simpler.
  • Furthermore, code changes need to occur in only
    one place.
  • However, when distributing a library, this can
    also be anathema to clients when used
    non-judiciously breaks encapsulation!

33
When to use inheritance
  • As with every semantic construct, there are no
    firm rules. Even general guidelines are not
    uniformly agreed upon.
  • A non-controversial statement is probably Be
    very careful not to overuse. Deep inheritance
    hierarchies are very hard to keep track of and
    maintain.
  • We will be exploring these issues constantly
    throughout the rest of the class.

34
The rules Certification fodder
  • The easier (but still sometimes subtle) question
    is what the exact rules are.
  • Divide rules up into several sections
  • instance variables
  • constrcutors
  • methods
  • issues with static ivs and methods

35
Rules for instance variables
  • First must understand concept of a package in
    Java.
  • A package is a collection of related class
    definition. For example, java.lang, java.util,
    java.util.regex, etc.
  • Classes that are not placed within a package are
    automatically in the default package.
  • Its generally a good idea to explicitily place
    all of your programs within a package.

36
Using classes from a package
  • Two ways to access classes from a package
  • use full package name
  • java.util.ArrayList x new java.util.ArrayList()
  • use import statement
  • import java.util.ArrayList
  • then can use just class name everywhere after
    import
  • What if names conflict?
  • compiler warning
  • must use full name to distinguish
  • Can also use wildcard for all classes in package
  • import javva.util.

37
Creating packages
  • To create a package, place the package identifier
    at the top of your source code.
  • e.g. package myjava.lib
  • This places the current class/classes in a
    package called myjava.lib (notice the lowercase
    convention for package names).
  • Important this class must be placed in a
    corresponding directory structure
    ROOT/myjava/lib.
  • Your CLASSPATH must contain ROOT

38
Class visibility
  • Classes themselves can be public or default (Im
    avoiding discussion of inner classes here)
  • public class Foo ...
  • class Foo ...
  • classes that are public are visible outside of
    their package
  • classes that are default are visible only within
    their package
  • Every source code file can have at most one
    public class but infinitely many package-scope
    classes.

39
Rules for instance variables
  • public accessible from any class
  • default accessible from any class within same
    package
  • protected default any subclass
  • private accessible only in class where defined.
  • note this includes any object created from that
    class

40
More on private ivs
  • If class B extends class A and A has private
    ivs, those ivs are part of class B.
  • However, those ivs cannot directly be accessed
    by class B.
  • This is an important distinction they are part
    of class B, but cannot be accessed directly by
    class B!?
  • class B would have to call non-private
    accessor/mutator methods to access As ivs.

41
Private vs. Protected ivs
  • To give direct access to superclass ivs, make
    them protected.
  • This is sometimes a very good idea, and sometimes
    a very bad idea. Ideas?
  • Horstmann points out that it breaks encapsultion.
    This is true, but the whole idea of inheritance
    breaks encapsulation.
  • General rule when constructing a library, be
    very careful when making anything non-private,
    espcially ivs. When programming within a
    package, requirements less stringent.

42
Rules for constructors
  • Unlike other methods and ivs, constructors are
    not inherited
  • When instantiating a class B that is a subclass
    of some class A
  • To call As constructor the first line of Bs
    constructor must be
  • super(...) // assume this is a valid
    constructor
  • super(...) may be ommitted if you wish to call
    the superclass default constructor.

43
Rules for methods
  • Visibility rules are the same for variables.
  • Public methods are often preferred way to access
    ivs.
  • A method in a superclass may be redefined in a
    subclass. This is called overriding (see next
    slide).
  • Regular rules of overloading apply.

44
Method 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.

45
Simple examples
Best to start abstract. Lets do data-only
classes class A private int iv1 public
int iv2 protected int iv3 int iv4 class
B extends A
46
Overriding 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.
47
Rules for static methods and fields
  • Static methods and fields cannot be overriden.
  • I dont ever do this. Please consult book if you
    are interested. It is not typical.

48
Abstract classes
  • Weve covered two extremes of inheritance
  • interfaces all methods are abstract in
    superclass and superclass (ie interface) serves
    to define common type
  • non-abstract superclasses all methods are
    non-abstract in superclass and subclass actually
    inheritents implementation.
  • good for code re-use
  • also good for defining common type

49
Abstract classes, cont.
  • Using abstract methods, we can actually program
    in between these two models.
  • This is done by creating superclasses that are
    mixtures of abstract and non-abstract methods
    plus ivs.
  • The non-abstract methods and ivs are inherited
    just like with regular classes.
  • The abstract methods are treated just like
    interface methods they must be implemented.

50
Rules for abstract classes
  • Any method in a class may be given the abstract
    keyword.
  • public abstract void foo(...)
  • If one or more methods in a class are abstract,
    the class itself must be declared abstract
  • abstract class Foo ...
  • Abstract classes may be subclassed, but not
    instantiated.

51
More on abstract classes
  • Abstract methods must have no meat.
  • It is not required that a subclass implement
    every (or any) abstract method in an abstract
    superclass.
  • However, if all abstract methods are not
    implemented in the subclass, the subclass must be
    declared abstract.
  • classes with all abstract methods are almost
    exactly like interfaces (what are the
    differences?)

52
Graphic view
pure impl inheritance
mixed impl/ interface inheritance
pure interface inheritance
regular class
interface
abstract class
Code Reuse
polymorphism
53
Example InputStream class
  • java.io.InputStream is a good case-study in
    abstract classes
  • InputStream is abstract because int read() is not
    implemented.
  • It is up to a subclass of InputStream to
    implement this method.
  • FileInputStream one such concrete subclass?
  • Question what is the advantage of this structure?
Write a Comment
User Comments (0)
About PowerShow.com