slide2.3_2009_r1 - Module 2.3 Module Abstract Classes and...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Module 2.3 Module Abstract Classes and Interfaces Abstract EE3206/EE5805 Java Programming & Applications 1 Intended Learning Outcomes To understand abstract type To To design and use abstract classes. To To declare interfaces to model weak inheritance relationships. relationships. To know the similarities and differences between an abstract class and an interface. abstract EE3206/EE5805 Java Programming & Applications 2 Screw and Screwdriver There are many kinds of screw heads. How do you find a screwdriver that works? screwdriver EE3206/EE5805 Java Programming & Applications 3 Interface We need an interface – a description about how description two parts can be put to work together! two In the software world, when one module uses another module, an interface is used to tell what functions the latter should provide. In Java, an interface iis a class-llike construct that s class ike In programmatically describes a set of methods descri set that conforming implementing classes must have. EE3206/EE5805 Java Programming & Applications 4 Case Study of Interface Bill, senior programmer, is writing a simple chess game. He needs a stack data structure for storing each move of a chess so that players can undo a move in the game. undo Mary, the assistant of Bill, is asked to implement the stack for his use. the Problem: Problem: How can they communicate the requirement / specification of the stack accurately? specification EE3206/EE5805 Java Programming & Applications 5 Possible Solutions Approach 1 - by text description The stack structure is a first-in-last-out data structure. The out It has three data fields, one constructor and four methods. The first data field is ......... methods. Approach 2 – by a class skeleton Bill may write a skeleton which has all the data fields, and method headers. The method bodies are then left to Mary to implement. left EE3206/EE5805 Java Programming & Applications 6 Analysis to the Solutions Approach 2 is obviously better than Approach 1 Less error-prone but not perfect Less The skeleton source may be modified by Mary unintentionally (e.g. rewriting the method headers) and then the resulted class will not conform to the original specification. original Is it possible to keep the skeleton information in a separate file (close-source) and then allow separate source) Mary to provide her implementation of the methods in another file? EE3206/EE5805 Java Programming & Applications 7 Interface Syntax An interface is similar to a class but contains only constants and class contains constants and abstract methods. When you want to declare a method or a class abstract When where the implementation is unknown at the moment, then you can use the abstract modifier. abstract modifier. Java uses the following syntax to declare an interface: Java public interface InterfaceName { constant declarations; method signatures; } public interface StackInterface { public static final int MAX_SIZE = 100; public abstract int pop(); } EE3206/EE5805 Java Programming & Applications 8 Interface is a Special Class An interface is treated like a special class in Java. Each interface is compiled into a separate bytecode file, just bytecode file, like a regular class. Because interfaces contain abstract methods which do Because do not define method bodies, you cannot create instances from an interface using the new operator as usual, but from but you can use an interface to declare a variable. variable. StackInterface s1; StackInterface StackInterface[ ] s2 = new StackInterface[10]; StackInterface EE3206/EE5805 Java Programming & Applications 9 Properties of Interface Interface has all data fields being constant (public static final) all all methods being abstract (public abstract) all These modifiers can be omitted. These public interface T1 { public static final int K = 1; public abstract void p(); } Equivalent public interface T1 { int K = 1; void p(); } A constant defined in an interface can be accessed like this: like InterfaceName.CONSTANT_NAME InterfaceName.CONSTANT_NAME e.g. T1.K e.g. EE3206/EE5805 Java Programming & Applications 10 Using Interface You can provide the method bodies (method implementations) for the abstract methods in another class. class. public interface StackInterface { public static final int MAX_SIZE = 100; public abstract int pop(); } public class MyStack implements StackInterface { private int top; private int elements; public int pop(){ return elements[top--]; } } EE3206/EE5805 Java Programming & Applications 11 The abstract Modifier The abstract The modifier abstract can also be applied to a class abstract Abstract class Abstract A mix of ordinary class and interface mix Usually contains both abstract and concrete (non-abstract) method Usually abstract) Usually be extended and the subclass overrides the abstract methods with a concrete method methods Cannot be instantiated Cannot public abstract class ClassName { …… …… } EE3206/EE5805 Java Programming & Applications 12 Properties of Abstract Class A class that contains abstract methods must be abstract. (but not necessarily be all abstract methods) (but It is possible to declare an abstract class that contains no abstract methods. If a subclass of an abstract superclass does not superclass does implement all the abstract methods, the subclass must be declared abstract. Similar to interface, an abstract class cannot be instantiated using the new operator, but can be used to declare variable. to EE3206/EE5805 Java Programming & Applications 13 Why Abstract Type? Abstract types are useful in that they can be used to define and enforce a protocol; a set of operations which all objects protocol set that implement the protocol must support. Abstract class is generally used as a base class for defining a new subclass. Its abstract methods force its subclasses to provide an implementation. provide The fact that Java language disallows instantiation of instantiation of abstract types and force subtypes to implement all needed functionality further ensures program correctness. correctness EE3206/EE5805 Java Programming & Applications 14 Interfaces vs. Abstract Classes In an interface, the data must be constants, but an abstract class can In ss have all types of data. have All methods of an interface are abstract, but an abstract class can have concrete methods. concrete Variables Constructors Methods Inheritance Abstract class No restrictions Constructors are invoked by subclasses through constructor chaining. An abstract class cannot be instantiated using the new operator. All variables must be public static final No constructors. An interface cannot be instantiated using the new operator. No restrictions. Single inheritance; extend one class only Interface All methods must be public abstract instance methods Multiple inheritance; implement more than one interface EE3206/EE5805 Java Programming & Applications 15 Interfaces vs. Abstract Classes All classes share a single root, the Object class, but there is no single root for Object class, interfaces. Like a class, an interface also defines a type. A variable of an iinterface type can nterface Like reference any instance of the class that implements the interface. If a class implements reference e. an interface, this interface plays the same role as a superclass. You can use an interface superclass You as a data type and cast a variable of an interface type to its subclass, and vice versa. as ubclass, Suppose that c iis an instance of Class2. c iis also an instance of Object, Class1, s s Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2. Interface1, Interface1_2 Interface2_2 Interface1_1 Interface1 Interface2_1 Object Class1 Class2 EE3206/EE5805 Java Programming & Applications 16 Interface vs. Abstract Class Abstract classes and interfaces can both be used to model common features. How Abstract features. do you decide whether to use an interface or a class? (Single Inheritance) In general, a strong is-a relationship that clearly describes a is that parent-child relationship should be modeled using classes. For example, a staff parent should member is a person. So their relationship should be modeled using class inheritance. member class (Multiple Inheritance) A weak is-a relationship, also known as an is-a-kind-of (Multiple relationship, is of relationship, iindicates that an object possesses a certain property. A weak is-a relationship ndicates is relationship can be modeled using interfaces. For example, all strings are comparable, relationship trings so the String class implements the Comparable interface. You can also use interfaces to overcome single inheritance restriiction if multiple ction You inheritance is desired. In the case of multiple inheritance, you have to design one as a inheritance have superclass, and others as interface. superclass and EE3206/EE5805 Java Programming & Applications 17 Using Interface and Abstract Class public interface Edible { /** Describe how to eat */ public String howToEat(); } class Animal { } class Chicken extends Animal implements Edible { public String howToEat() { return "Fry it"; } } class Tiger extends Animal { } EE3206/EE5805 Java Programming & Applications 18 Using Interface and Abstract Class public interface Edible { /** Describe how to eat */ public String howToEat(); } class abstract Fruit implements Edible { } class Apple extends Fruit { public String howToEat() { return "Make apple pie"; } } class Orange extends Fruit { public String howToEat() { return "Make orange juice"; } } EE3206/EE5805 Java Programming & Applications 19 Testing Subclasses public interface Edible { /** Describe how to eat */ public String howToEat(); } public class TestEdible { public static void main(String args) { Object objects = {new Tiger(), new Chicken(), new Apple()}; for (int i = 0; i < objects.length; i++) showObject(objects[i]); } public static void showObject(Object object) { if (object instanceof Edible) // You cannot eat Tiger System.out.println(((Edible)object).howToEat()); } } EE3206/EE5805 Java Programming & Applications 20 Implements Multiple Interfaces class Chicken extends Animal implements Edible, Comparable { int weight; public Chicken(int weight) { this.weight = weight; } public String howToEat() { Two interfaces return "Fry it"; } public int compareTo(Object o) { return weight – ((Chicken)o).weight; } } EE3206/EE5805 Java Programming & Applications 21 The Marker Interface A marker interface is an empty interface that DOES is DOES NOT contain constants or methods. It is used to denote a class possesses certain desirable denote class properties. Whereas a typical interface specifies functionality (in the interface specifies form of method declarations) that an implementing class must support. class The mere presence of such an interface indicates indicates specific behavior on the part of the implementing class EE3206/EE5805 Java Programming & Applications 22 ...
View Full Document

Ask a homework question - tutors are online