Download Lecture 7

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CompSci 230
Software Construction
Lecture 7: Object-Oriented Design, Part 4
Agenda

Topics:





Abstract classes in Java
Interfaces in Java
Reference data types
Java syntax: six important keywords
Reading

In The Java Tutorials:


2
What is an Interface?, in the Object-Oriented Programming Concepts Lesson
The Interfaces and Inheritance Lesson
COMPSCI 230: Impl1
final

The final keyword can be applied to prevent the extension
(over-riding) of a field, argument, method, or class.




Final field: constant
Final argument: cannot change the data within the called method
Final method: cannot override method in subclasses
Final class: cannot be subclassed (all of its methods are implicitly final
as well)
class ChessAlgorithm {
. . .
final void nextMove(
ChessPiece pieceMoved, BoardLocation newLocation ) {
\\ body of nextMove – can’t be overriden
}
}
3
COMPSCI 230: Impl1
Abstract Classes

Sometimes, it’s appropriate to partly-implement a class which we
don’t really want to have instantiated in its own right



Abstract classes may include some abstract methods.


4
E.g., every UniversityMember will be a Lecturer or Student of sorts (or
GeneralStaff, or some other subclass) – so we’d expect to instantiate
subclasses only. We’ll never want to instantiate a UniversityMember as
such, but we want to bundle common functionality in the class.
Abstract classes allow code to be reused in similar implementations.
Abstract methods have a signature, but no body (and are declared as
abstract)
Any subclass that is not in itself abstract must implement the abstract
methods (i.e., add a body)
COMPSCI 230: Impl1
Example: Abstract class & method
import java.util.*;
// for the ArrayList class
public abstract class UniversityMember extends Person {
public String auid;
protected ArrayList<String> courses;
public UniversityMember() {
courses = new ArrayList<String>();
}
Superclass of an abstract class doesn’t
need to be abstract itself!
public abstract void getExamResults();
Abstract method: no body
public final void identify() {
System.out.print("I'm acting as a university member! ");
System.out.print("My name is " + name + ". ");
System.out.println("Gaudeamus igitur!");
}
}
Can’t do this:
UniversityMember um = new UniversityMember();
5
COMPSCI 230: Impl1
Example: Subclass of abstract class
import java.util.*;
public class Lecturer extends UniversityMember {
public Lecturer() {
super(); // call superclass constructor (UniversityMember())
}
…
public void moveAbout() {
System.out.println("I stride forward!");
}
Implementation of abstract
method. Without this, the
Lecturer class will not compile.
public void getExamResults() {
System.out.println("The 230 class did just fine apart from a few
stragglers.");
}
}
6
Can do this:
UniversityMember um = new Lecturer();
um.getExamResults();
COMPSCI 230: Impl1
Example: Using abstract classes and methods
public class UniversityExampleProgram {
public static void main(String[] args) {
System.out.println("*** Person object referenced by Person variable:");
Person p = new Person();
p.name = "Somebody";
p.identify();
p.moveAbout();
System.out.println("*** Lecturer object referenced by Lecturer variable:");
Lecturer l = new Lecturer();
l.name = "Professaurus";
l.identify();
l.moveAbout();
l.getExamResults();
System.out.println("*** Lecturer object referenced by UniversityMember variable:");
UniversityMember um = l;
um.getExamResults();
}
}
7
COMPSCI 230: Impl1
Interfaces in Java 7





An interface is like a class, but with no bodies in the methods. It
may define constants (public static final) but no runtime
variables.
Any actual class declaration that indicates that it implements a
particular interface must implement all
Usually, an interface is public.
An interface provides a standard way to access classes which could be
implemented in many different ways.
The Java Tutorials:


8

“There are a number of situations in software engineering when it is important
for disparate groups of programmers to agree to a ‘contract’ that spells out how
their software interacts.”
“Each group should be able to write their code without any knowledge of how
the other group's code is written.”
“Generally speaking, interfaces are such contracts.”
COMPSCI 230: Impl1
Interfaces in Java 8

In Java 8, an interface may contain



In any OO language, an interface



Java compilers can enforce contracts, by refusing to compile classes
whose implementations might “partially implement” an interface.
Java is a tightly-specified language.

9
cannot be instantiated, and
defines a “contract” which any realization of the interface must fulfil.
Java is a strongly-typed language.


default implementations of instance methods, and
implementations of static methods.
If a compiler allows instantiations of incompletely implemented interfaces,
then it is not a Java compiler.
COMPSCI 230: Impl1
Example
•
•
•
10
Vehicle and Tent classes do not have a common superclass
Both implement the interface Relocatable
Accommodation is an abstract class
COMPSCI 230: Impl1
Example: Relocatable.java
public interface Relocatable {
public void moveTo(double longitude, double latitude);
}
11
COMPSCI 230: Impl1
Example: Vehicle.java
public class Vehicle implements Relocatable {
public String make;
public String model;
public void moveTo(double longitude, double latitude) {
System.out.print("Current position: " + Math.abs(longitude));
if (longitude < 0) {
System.out.print("W, ");
}
else
{
System.out.print("E, ");
}
System.out.print(Math.abs(latitude));
if (latitude < 0) {
System.out.println("S");
}
else
{
System.out.println("N");
}
}
}
12
COMPSCI 230: Impl1
Example: Accommodation.java
public abstract class Accommodation {
protected double longitude;
protected double latitude;
public Accommodation(double longitude, double latitude) {
this.longitude = longitude;
this.latitude = latitude;
}
public void getLocation() {
…
}
}
13
COMPSCI 230: Impl1
Example: Tent.java
public class Tent extends Accommodation implements Relocatable {
public Tent(double longitude, double latitude) {
super(longitude, latitude);
}
public void moveTo(double longitude, double latitude) {
System.out.println("Packing up my tent and going elsewhere...");
this.longitude = longitude;
this.latitude = latitude;
}
}
14
COMPSCI 230: Impl1
Example: Using the Relocatable interface
public class InterfaceDemo {
public static void main(String[] args) {
Vehicle myCar = new Vehicle();
myCar.moveTo(174.769621, -36.851582); // calling method from Relocatable
//interface
Relocatable myMobileThing = myCar; // OK: Vehicle implements Relocatable
Hotel myHotel = new Hotel(179.194565, -8.523872);
// myHotel.moveTo(174.764471,-36.878053); // not possible!
Tent myTent = new Tent(179.194565, -8.523872);
myTent.moveTo(174.764471,-36.878053); // OK: Tent implements Relocatable
myMobileThing = myTent; // Allowed: a Tent is Relocatable!
myMobileThing.moveTo(174.928663, -36.767782); // Can move Relocatables
// regardless of class
myTent.getLocation(); // I'm camped in the new spot!
}
}
15
COMPSCI 230: Impl1
Implementations as contracts

A class which realizes an interface must provide an implementation of
every method defined within the interface



A class can implement many interfaces.


A class may implement some additional methods (but these extra methods
aren’t accessible through this interface)
Beware: adding another method to an existing Interface will “break” every
current implementation of this Interface!
In Java: implements MyInterface1, MyInterface2, …
An interface can extend other interfaces (much like inheritance)

Extension is the preferred way to add new methods to an Interface.


16
Why?
In Java, classes are less extendible than interfaces, because a class can extend
at most one other class (“single inheritance”).
class MountainBike extends Bicycle { … }
COMPSCI 230: Impl1
Strange interfaces!
public interface EventListener {
// No constants
// No method signatures!
}
 “A tagging interface that all event listener interfaces must extend.”

[http://docs.oracle.com/javase/6/docs/api/java/util/EventListener.html]
Why?


17
At first glance, this is worse than useless! One more name for the Java
programmer to remember…
This interface allows programmers, and the Java compiler, to distinguish
event-listeners from all other types of classes and interfaces.
 Event-listeners are important, and they behave quite differently to a
regular class. (Later, you’ll learn about inversion of control…)
COMPSCI 230: Impl1
Using an Interface as a Type

Each interface defines a new reference data type.


18
In this respect, interfaces are types in the same way that classes are types
A variable whose type is an interface can only store references to objects
that are an instance of a class that implements the interface.
[http://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html]
COMPSCI 230: Impl1
Review




Abstract classes in Java
Interfaces in Java
Types in Java
Six important keywords:






19
final
interface
implements
abstract
super
this
COMPSCI 230: Impl1
Review questions








20
If I write an abstract class, what do I need to do before I can instantiate
an object that belongs to this class?
If I have an abstract class, can I declare a variable whose type is the
abstract class?
Can a non-abstract class contain an abstract method?
Can an abstract class have a non-abstract superclass?
Can I implement an abstract method in the subclass of a direct subclass,
if I’m not implementing it in the direct subclass itself?
Can a method be both abstract and final?
What condition do two classes need to meet in order to implement the
same interface?
If I have a variable whose type is that of an interface, and I want to invoke
a method on an object it references, which methods of the object can I
invoke?
COMPSCI 230: Impl1