Download Abstract and Nested Classes

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

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

Document related concepts
no text concepts found
Transcript
Abstract and Nested Classes
• Abstract classes:
– Incomplete abstract classes.
– Complete abstract classes.
– Comparison with interfaces.
• Nested Classes:
– Static nested classes.
– Inner classes.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
1
Abstract Classes
• Class has abstract prefix.
• Instances may not be constructed.
– Incomplete methods: just a header.
– Method has abstract prefix.
• Implicit in interface definitions.
• Objects have no meaningful existence.
• Class elements used by defining sub classes.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
2
The Abstract Number Class
public abstract class Number implements Serializable {
public abstract int intValue();
public abstract long longValue();
public abstract double doubleValue();
public abstract float floatValue();
public byte byteValue(){
...
}
public short shortValue(){
...
}
...
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
3
Incomplete Abstract Classes
• Define a common interface for multiple sub
classes.
• Sub class implementations vary.
– Implementation of floatValue, in Number
sub classes, depends on type of attribute.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
4
The Double Sub Class
public class Double extends Number {
public Double(double value){
this.value = value;
}
...
// This probably involves loss of information.
public float floatValue(){
return (float) doubleValue();
}
...
// The value being wrapped.
private final double value;
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
5
Complete Abstract Classes
• No abstract methods.
• Independent instantiations have no
meaning.
– ChessPiece super class of Rook, Knight,
etc.
– Sub classes provide additional or overriding
functionality.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
6
Abstract Class or Interface?
• Interface methods are abstract.
• Interfaces do not have constructors.
• Abstract classes avoid the need to define
duplicate method bodies.
• Multiple inheritance.
– Extending an abstract class prevents extension
of a second class.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
7
Object Cloning
• All classes inherit a clone method.
• Returns an identical copy.
– A shallow copy, by default.
– A deep copy is often preferable.
• The (empty) Cloneable interface must be
implemented.
– CloneNotSupportedException
OOP with Java, David
J. Barnes
Abstract and Nested Classes
8
A Cloneable Point
class Point implements Cloneable {
...
public Object clone() {
try{
// A shallow copy.
return super.clone();
}
catch(CloneNotSupportedException e){
// This should never happen!
throw new Error("Cloning error: "+e);
}
}
...
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
9
Preventing Cloning
• Prevention might be necessary.
– A unique attribute - database lock or open file
reference.
• Not sufficient to omit Cloneable.
– Sub classes might implement it.
• clone should throw an exception:
– CloneNotSupportedException.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
10
An Unclonable Class
class NotCloneable {
...
// Explicitly prevent sub class cloning.
public Object clone()
throws CloneNotSupportedException {
throw new CloneNotSupportedException("...");
}
...
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
11
Nested Classes
• Static Nested Classes (aka Nested TopLevel Classes!?).
• Used to show strong coupling between two
classes.
– VariableController and
HeaterLevelException.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
12
class VariableController extends HeaterController {
// Class constants for basic temperatures.
public static final int DefaultLevel = 16,
MinLevel = 5, MaxLevel = 30;
// An illegal temperature level has been set.
public static class HeaterLevelException
extends RuntimeException {
public HeaterLevelException(String message){
super(message);
}
}
// The attached heater's current level.
public int getLevel(){
...
}
...
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
13
Static Nested Class Names
• Nested class has a qualified name.
– VariableController.HeaterLevelException
• Separate .class file created.
– VariableController$HeaterLevelException.class
• Qualified name used outside the enclosing class.
– catch(VariableController.HeaterLevelException e)
OOP with Java, David
J. Barnes
Abstract and Nested Classes
14
Inner Classes
• Non-static nested classes.
• Instances only exist within the context of an
enclosing object.
• May not have static members.
• May access private members of the
enclosing class.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
15
Inner Class Roles
• Used to fulfill distinct roles in support of an
enclosing object.
–
–
–
–
Subordinate inner class.
Interpretational inner class.
Local inner class.
Anonymous inner class.
• Very common in supporting GUIs.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
16
Subordinate Inner Classes
• Used to break up a single large class.
• Implement subordinate sub-tasks.
– E.g., logging a ship's movements.
• Keeps enclosing class less cluttered.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
17
public class LoggingShip extends SimpleShip {
...
public void move(){
super.move();
getLogger().log();
}
protected class ShipLog {
protected void log(){
Position p = new Position(getX(),getY());
getLog().add(p);
}
protected LinkedList getLog(){
return positionLog;
}
private LinkedList positionLog = new LinkedList();
}
...
private final ShipLog logger = new ShipLog();
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
18
Interpretational Inner Classes
• Interpreting an object’s data to outside
objects.
– Independently of the internal representation.
– E.g. Iterator and Enumeration
implementations.
• DataValues - a collection of numbers.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
19
public class DataValues {
public void add(double d){
getNumbers().add(new Double(d));
}
public double get(int index) throws
IndexOutOfBoundsException {
Double d = (Double) getNumbers().get(index);
return d.doubleValue();
}
public int numItems(){
return getNumbers().size();
}
...
protected LinkedList getNumbers(){
return numbers;
}
private final LinkedList numbers = new LinkedList();
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
20
public class DataValues {
public Iterator getPositives(){
return new PositiveSelector();
}
protected class PositiveSelector implements Iterator {
public boolean hasNext(){
return nextPosition() >= 0;
}
public Object next() throws NoSuchElementException {
int i = nextPosition();
if(i >= 0){
Object o = getNumbers().get(i);
setIndex(i+1);
return o;
}
else{
throw new NoSuchElementException();
}
}
...
}
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
21
Local Inner Classes
• A class defined within a method.
– Permitted within any block.
• Instances may only be created from within
that method.
– No visibility modifier is used.
• Instances may access the method’s final
variables and arguments.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
22
public class DataValues {
public Iterator selectAbove(final double limit){
class AboveSelector implements Iterator {
...
protected int nextPosition(){
int i = getIndex();
final int howMany = numItems();
while(i < howMany){
if(get(i) > limit){
return i;
}
i++;
}
return -1;
}
}
return new AboveSelector();
}
...
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
23
Anonymous Classes
• Local classes often do not require a name.
– When they implement an interface or extend a
super class.
– When definition and creation are closely linked.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
24
public class DataValues {
...
public Iterator selectAbove(final double limit){
return new Iterator() {
public boolean hasNext(){
...
}
public Object next(){
...
}
...
};
}
...
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
25
Anonymous Classes in GUIs.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Picture extends JFrame {
Container contents = getContentPane();
// Add a button to quit the application.
JButton quit = new JButton("Quit");
quit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
contents.add(quit,"South");
...
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
26
Inner Classes and this
class Outer {
// 'this' accessible from here.
...
class Middle {
// 'this' and 'Outer.this' accessible from here.
...
class Innermost {
// 'this', 'Middle.this' and 'Outer.this'
// accessible from here.
...
}
...
private Innermost i = new Innermost();
}
...
private Middle m = new Middle();
}
OOP with Java, David
J. Barnes
Abstract and Nested Classes
27
Review
• Abstract classes are incomplete and must be
sub classed to be useful.
• Abstract classes offer an alternative to
interfaces where partial implementation is
useful.
• Classes implement cloning by
implementing the Cloneable interface.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
28
Review (cont.)
• Nested classes may be static nested classes
or inner classes.
• Inner class instances always exist within the
context of an enclosing object.
• Inner classes have access to the private
members of their enclosing class.
• Inner classes are useful for fulfilling a range
of roles within their enclosing class.
OOP with Java, David
J. Barnes
Abstract and Nested Classes
29
Related documents