Title: MIT AITI 2002
1MIT AITI 2002
- Abstract Classes, Interfaces
2Abstract Classes
- What is an abstract class?
- An abstract class is a class in which one or
more methods is declared, but not defined. (The
programmer has not yet written code for a few
methods). These methods have an abstract keyword
in their signature. - public abstract class Employee
- private String name
- public Employee(String name) .
- public abstract double getSalary()
-
3Advantages
- Classes can now be very general in a class/type
hierarchy. This allows more abstraction in object
oriented programming. - For example, we could have an Employee class in
our program from which Managers, SalesManagers,
Engineers, etc. inherit. - An Employee class is too abstract to ever use in
a computer system but it can hold name, address,
status, etc. that is in common to all the
subclasses. - Employee is an abstract class Employee objects
cannot be created / hired, but subclass objects,
such as Engineer, can be hired. - Have more control over inheritance in a
class/type hierarchy.
4Simple Examples
- An Animal Type Hierarchy
- An abstract Animal class could have an abstract
method such as public abstract void makeSound() - All derived classes (Fish, Dog, Cat) have their
own specific makeSound() methods. - An Instrument Hierarchy
- An abstract Instrument class could have methods
like public abstract void playInstrument() - All derived classes (Horn, Violin, Piano) have
their own specific behavior.
5A File System Example
- Writing a File System Application
- We want a general FileSystemObject abstract
class. - All file system objects should have certain
behavior (e.g. we can open a file system object)
but we dont know yet how each type will
implement this behavior. - A Files open() method will display the text in
the file, while a Directorys open() method might
display other files in the directory. We can
declare the open() method as abstract.
6Design Picture
FileSystemObject
contains
Directory
File
A Directory contains other FileSystemObject types
(which are either other directories or files in
this case). Another FileSystemObject could be a
Link to another directory.
7A Shape Example
- Imagine writing a drawing application.
- We need to represent a Shape class.
- Shapes are too general to draw we only know how
to draw specific shapes like circles or
rectangles. - The Shape abstract class can define a common set
of methods that all shapes must implement, so our
drawing application can count on certain methods
(behaviors) being available in every concrete
shape class. - The Shape abstract class can implement some
methods that every subclass must use, for
consistency e.g., object ID, object type
8Writing a Shape Class
- public abstract class Shape
- // Drawing function must be implemented in each
- // derived class.
- public abstract void draw()
- // Error function must be implemented in each
- // derived class. A Default is available here.
- public void error(String message)
- // Each derived class must have
- // and use this implementation (final keyword)
- public final int shapeType()
-
- class Square extends Shape
- class Circle extends Shape
9An Abstract method
- Shape is an abstract class (keyword)
- Shape has an abstract method draw()
- No objects of type Shape can be created
- draw() must be redeclared by any concrete
(non-abstract) class that inherits it - There is no definition of draw() in Shape
- This says that all Shapes must be drawable, but
the Shape class has no idea of how to draw
specific shapes
10A Non-abstract method
- Shape has a non-abstract method error()
- Every derived class must have an error method
- Each derived class may handle errors as it
wishes - It may define its own error function.
- It may use the super class implementation as a
default - This can be dangerous if new derived classes are
added and programmers fail to redefine
non-abstract methods, the default may be invoked
but may do the wrong thing. - E.g. If an abstract Bird class defines a
non-abstract fly() method, and we define a new
Penguin type that extends the Bird class, the
Penguin will have a fly() default behavior unless
the programmer overrides the method.
11Final Method
- Shape has a final method shapeType()
- Final method is invariant across derived classes
- Behavior is not supposed to change, no matter how
specialized the derived class becomes - Super classes should have a mix of methods
- In general, super classes will need both abstract
and non-abstract methods.
12Preventing Inheritance
- To prevent someone from inheriting from your
class, declare it final - final class RandomClass
- You can also prevent individual methods from
being overridden (redefined) in subclasses by
declaring them final - final void getData()
- This would not allow a subclass to redefine
getData()
13Interface Definition
- An interface is a contract for a class. An
interface specifies a set of methods a class must
implement. - An interface is similar to an abstract class
except all methods are abstract automatically.
An interface has no constructors, only variables
and methods.
14Interfaces
- Interfaces specify but do not implement methods
provide function declarations only. - A class that implements the interface must
implement all its methods - You may then invoke methods on this class that
rely on the interface. Examples - If your class implements the Comparable or
Comparator interface, you can put objects of your
class into Arrays and use the Arrays.sort()
method - You will use interfaces frequently in Swing (GUI)
15Interface Details
- Interfaces are like an abstract class but
- If they were implemented as an abstract class, a
subclass could only inherit from one superclass - Multiple interfaces can be inherited (e.g.,
Comparable and Cloneable) in your class - Interfaces cannot be instantiated
- Comparable list new Comparable()
- You can declare objects to be of type interface
- Comparable list
- They can be names for objects of a class that
implements the interface - Comparable list new MySortClass()
- Interfaces may contain methods and constants
- public interface Rotatable
- void rotate(double theta)
- double MAX_ROTATE 360
16Interfaces and inheritance
- Interfaces can be inherited
- A Smart Interface
- public interface Smart
- double hoursStudied(Date specificDate)
-
- A Genius Interface extends Smart
- public interface Genius extends Smart
- boolean isThinking()
-
17Interface Example I
- public interface HelpfulConstants
- double OUNCE_TO_GRAM 28.34
- double WATT_TO_HP 745.1
An interface can be helpful to store constants in
a program. The variables in an interface are
always public static final by default so there is
no need to specify any access modifiers.
18Interface Example I
- public class MyProgram implements
HelpfulConstants - public static void main(String args)
- System.out.println(10 ounces equals
- (ONCE_TO_GRAM 10) grams.
-
By implementing the HelpfulConstants Interface,
MyProgram class is able to access any variables
defined in the interface.
19Interface Example II
- class Student implements Comparable
- public int compareTo(Object b)
We can implement java defined interfaces. For the
Comparable interface, we must provide one method
called compareTo(Object b).
20Interface Example II
- class Student implements Comparable
- private String name
- private int terms
- public Student(String n, int t)
- name n terms t
- public String getName() return name
- public int getTerms() return terms
- public int compareTo(Object b)
- Student two (Student) b
- if (terms lt two.terms)
- return -1
- else if (terms gt two.terms)
- return 1
- else
- return 0
21Interface Example II
- import java.util.
- public class Application
- public static void main(String args)
- Student list new Student4
- list0 new Student("Mary", 6)
- list1 new Student("Joan", 4)
- list2 new Student("Anna", 8)
- list3 new Student("John", 2)
- Arrays.sort(list)
- for (int i 0 i lt list.length i)
- Student s listi
- System.out.println(s.getName() " "
- s.getTerms())
-
-
22Interface Example III
Writing an Interface Example We want to define
a Path interface. A path is a sequence of any
object type. (For example, we could have a path
of nodes, points, roads, etc.) We only need a
method to extend a path. This method returns a
new Path with an additional Object added. //
Defines a Path contract. All paths will be
extendable. public interface Path public Path
extend(Object n)
23Interface Example III
Implementing an Interface Note An interface
does not specify a constructor i.e. how a
specific Path object is to be made. It merely
states that all Paths should be
extendable. public class StreetRoute implements
Path // Data fields to store path. private
Vector pathElements // Constructors //
Method that Implements Path contract. public
void extend(Object n) pathElements.addElement(
n)
24Summary
- Have learned all essential concepts for objects.
- 1. How to Construct a new Object Type
- 2. How to encapsulate data within an
abstract type using access modifiers.
Object fields. - 3. How to write methods behavior of an
object. - 4. How to write classes (Line class) from
defined classes (Point class). Systems of
objects I. - 5. How to extend a superclass Inheritance
Able to modify, and reuse classes. - 6. How to write abstract classes.
- 7. How to design using interfaces to
specify certain behavior among similar
classes/types.
25Further Topics
- Study Java API. We can now extend, use, and
understand Java classes given to us. - Further Topics File Input and Output (java.io)
set of classes in a library given for file
manipulation. - Further Topics Swing Graphics Set of classes
in a library given for graphics programming
windows, mouse / keyboard events, etc. - Further topics depend on object concepts learned
up to this point. No new concepts!