Interfaces, Inhteritance, Polymorphism. What is an Java interface? Like a class but only contains...
-
date post
20-Dec-2015 -
Category
Documents
-
view
219 -
download
0
Transcript of Interfaces, Inhteritance, Polymorphism. What is an Java interface? Like a class but only contains...
Interfaces, Inhteritance, Polymorphism
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.
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.
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!
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
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
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.
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.
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!
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.
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.
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!
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”.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Ineritance
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.
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.
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).
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.
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.
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!
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.
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
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.
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.*;
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
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.
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
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.
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.
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.
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.
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.
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{
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.
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.
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
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.
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.
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?)
Graphic view
pure implinheritance
mixed impl/interface
inheritance
pure interfaceinheritance
regular class interfaceabstract class
CodeReuse
polymorphism
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?