interfaces, inhteritance, polymorphism. what is an java interface? like a class but only contains...

53
Interfaces, Inhteritance, Polymorphism

Post on 20-Dec-2015

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Interfaces, Inhteritance, Polymorphism

Page 2: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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 publickeywords are implied,so the shorthand is recommended.

Page 3: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 4: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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!

Page 5: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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 eitherMyConstants.PI or just PI by any class that implements the interface

Page 6: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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

Page 7: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 8: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 9: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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!

Page 10: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 11: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Generic examples of subtyping

class Circle implements Drawable, Scalable{ ...

Circle aCircle;Drawable aDrawable;Scalable aScalable;

aCircle = new Circle(); //okaCircle = new Drawable(); //BAD!aDrawable = new Circle();//okaScalable = new Circle(); //ok

1,3,4 are ok because a Circle object is created and it is assignedto a declared type of either Circle or one of its supertypes.

Page 12: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

More examples

Drawable aDrawable;Circle aCircle;aCircle = new Circle();//fineaDrawable = aCircle;//fine – aDrawable is type superclass

aDrawable = new Circle();aCircle = aDrawable; //NO; cannot assign more general to //more specific without an explicit //castaCircle = (Circle) aDrawable; //this is ok – explicit cast!

Page 13: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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 Java’s very strong typing. It is your best friend. Narrowing is also known as “downcasting”.

Page 14: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.1. with a try-catch block (later)2. 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.

Page 15: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 16: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Using Upcasting in method callsImagine there is a class Renderer that has a method Renderthat can operate on any object that knows how to morphany 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

Page 17: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Comparable interface

Another good example is Java’s 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.

Page 18: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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 Java’s 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.

Page 19: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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 implementsFooInterface2 must implement both of these.

Page 20: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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

We’ll cover a few ways in which interfaces are typically used.

Page 21: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Some interface uses

1. To simply clarify the the functionality associated with a particular abstraction.

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

3. To implement callbacks, such as in GUI programming

4. To write more general, implementation depending code that is easy to extend and maintain.

5. To simulate global constants.

Page 22: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 23: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 24: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 25: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 26: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Ineritance

Page 27: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 28: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Inheritance syntax

For one class to be a subclass of another, we usethe extends keyword:

class GradStudent extends Student{ ...}class Manager extends Employee{...} etc.

The superclass requires no special syntax.

Page 29: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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

Page 30: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 31: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Overriding exampleclass A{ public void m1(){...}}

class B extends A{ public void m1(){...}}

For objects of class B, its own unique version of m1 will becalled. We say that the method m1 in B overrides the method m1 in its superclass.

Page 32: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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!

Page 33: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 34: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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 iv’s and methods

Page 35: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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

It’s generally a good idea to explicitily place all of your programs within a package.

Page 36: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.*;

Page 37: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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

Page 38: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Class visibility Classes themselves can be public or default (I’m

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.

Page 39: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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

Page 40: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

More on private iv’s

If class B extends class A and A has private iv’s, those iv’s are part of class B.

However, those iv’s 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 A’s iv’s.

Page 41: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Private vs. Protected iv’s To give direct access to superclass iv’s, 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 iv’s. When programming within a package, requirements less stringent.

Page 42: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Rules for constructors

Unlike other methods and iv’s, constructors are not inherited

When instantiating a class B that is a subclass of some class A:– To call A’s constructor the first line of B’s

constructor must be super(...); // assume this is a valid

constructor– super(...) may be ommitted if you wish to call

the superclass default constructor.

Page 43: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Rules for methods

Visibility rules are the same for variables. Public methods are often preferred way to

access iv’s. A method in a superclass may be redefined

in a subclass. This is called overriding (see next slide).

Regular rules of overloading apply.

Page 44: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 45: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Simple examples

Best to start abstract. Let’s do data-only classes:

class A{ private int iv1; public int iv2; protected int iv3; int iv4;}

class B extends A{

Page 46: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Overriding exampleclass A{ public void m1(){...}}

class B extends A{ public void m1(){...}}

For objects of class B, its own unique version of m1 will becalled. We say that the method m1 in B overrides the method m1 in its superclass.

Page 47: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Rules for static methods and fields Static methods and fields cannot be

overriden. I don’t ever do this. Please consult book if

you are interested. It is not typical.

Page 48: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Abstract classes

We’ve 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

Page 49: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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 iv’s.

The non-abstract methods and iv’s are inherited just like with regular classes.

The abstract methods are treated just like interface methods – they must be implemented.

Page 50: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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.

Page 51: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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?)

Page 52: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

Graphic view

pure implinheritance

mixed impl/interface

inheritance

pure interfaceinheritance

regular class interfaceabstract class

CodeReuse

polymorphism

Page 53: Interfaces, Inhteritance, Polymorphism. What is an Java interface?  Like a class but only contains abstract methods and final variables example: interface

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?