25
MIT AITI 2002 Abstract Classes, Interfaces

MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Embed Size (px)

Citation preview

Page 1: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

MIT AITI 2002

Abstract Classes, Interfaces

Page 2: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Abstract 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(); }

Page 3: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

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

Page 4: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

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

Page 5: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

A 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 don’t know yet how each type will implement this behavior.A File’s open() method will display the text in the file, while a Directory’s open() method might display other files in the directory. We can declare the open() method as abstract.

Page 6: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Design Picture

FileSystemObject

Directory File

contains

A Directory contains other FileSystemObject types (whichare either other directories or files in this case). Another FileSystemObject could be a Link to another directory.

Page 7: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

A 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

Page 8: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Writing 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 {…}

Page 9: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

An 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

Page 10: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

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

Page 11: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

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

Page 12: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Preventing 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 finalfinal void getData() { … This would not allow a subclass to redefine

getData()

Page 13: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

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

Page 14: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

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

Page 15: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Interface 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 instantiatedComparable list= new Comparable();

You can declare objects to be of type interfaceComparable list;

They can be names for objects of a class that implements the interface:Comparable list= new MySortClass();

Interfaces may contain methods and constantspublic interface Rotatable { void rotate(double theta); double MAX_ROTATE= 360; }

Page 16: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Interfaces and inheritance

Interfaces can be inherited A Smart Interfacepublic interface Smart {

double hoursStudied(Date specificDate); }

A Genius Interface extends Smartpublic interface Genius extends Smart {

boolean isThinking(); }

Page 17: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Interface 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 alwayspublic static final by default so there is no need to specify any access modifiers.

Page 18: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

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

Page 19: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Interface Example II

class Student implements Comparable {

public int compareTo(Object b) { }

}

We can implement java defined interfaces.For the Comparable interface, wemust provide one method called compareTo(Object b).

Page 20: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Interface 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 < two.terms) return -1; else if (terms > two.terms) return 1; else return 0; }}

Page 21: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Interface Example IIimport java.util.*;public class Application { public static void main(String[] args) { Student[] list= new Student[4]; list[0]= new Student("Mary", 6); list[1]= new Student("Joan", 4); list[2]= new Student("Anna", 8); list[3]= new Student("John", 2); Arrays.sort(list); for (int i= 0; i < list.length; i++) { Student s = list[i]; System.out.println(s.getName() + " "

+ s.getTerms()); } } }

Page 22: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Interface 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);}

Page 23: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Interface Example IIIImplementing 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);

}}

Page 24: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Summary

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.

Page 25: MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,

Further 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!