Presentation is loading. Please wait.

Presentation is loading. Please wait.

04 - Abstract Classes and Interfaces. 2 © S. Uchitel, 2004 Abstract Classes Unlike classes, these cannot be instantiated. Unlike classes, these cannot.

Similar presentations


Presentation on theme: "04 - Abstract Classes and Interfaces. 2 © S. Uchitel, 2004 Abstract Classes Unlike classes, these cannot be instantiated. Unlike classes, these cannot."— Presentation transcript:

1 04 - Abstract Classes and Interfaces

2 2 © S. Uchitel, 2004 Abstract Classes Unlike classes, these cannot be instantiated. Unlike classes, these cannot be instantiated. Like classes, they introduce types. Like classes, they introduce types.  but no objects can have as actual type the type of an abstract class. Why use them? Why use them?  Because there is a set of common features and implementation for all derived classes but...  We want to prevent users from handling objects that are too generic (Example 1)  We cannot give a full implementation for the class (Example 2) AbstractClass Italics indicates abstract

3 3 © S. Uchitel, 2004 Example 1 The problem: The problem:  Students are either undergraduate, PhD or MsC.  We want to guarantee that nobody creates a Student object. The application always creates a specific kind of Student. The solution: The solution:  Declare Student as abstract. Why have the Student class in the first place? Why have the Student class in the first place?  A common implementation of common aspects of all students. (e.g. setLogin() and getLogin())  A place holder in my hierarchy that corresponds to a significant concept in my problem domain  To handle all students independently of their subclass using type Student and polymorphism. PhdStudentMscStudentUndergrad Student getLogin() setLogin(String)

4 4 © S. Uchitel, 2004 Abstract Classes in Java public abstract class Student { protected String login, department, name; public Student() { login = “”; department = “”; name = “”; } public void setLogin(String login) { this.login = new String(login); } public String getLogin() { return new String(login); }} PhdStudent Student getLogin() setLogin(String) public class PhdStudent extends Student{ private String supervisor; public void setSupervisor(String login) {... PhdStudent is said to be a concrete class

5 5 © S. Uchitel, 2004 Example 2 The Problem The Problem  How do we calculate the area of an arbitrary shape?  We cannot allow Shape objects, because we cannot provide a reasonable implementation of getArea(); The Solution The Solution  So we declare the Shape to be an abstract class.  Furthermore, we declare getArea() as an abstract method because it has no implementation Why have the Shape class in the first place? Why have the Shape class in the first place?  Same reasons as for Student: a common implementation, a placeholder in the hierarchy and polymorphism.  Plus that we want to force all shapes to provide an implementation for getArea(); TriangleCircleRectangleHexagon getArea(): double setColour(int) Shape

6 6 © S. Uchitel, 2004 Abstract Methods in Java public abstract class Shape { final static int BLACK = 0; private int colour; public Shape() { colour = BLACK; } public void setColour(int c) { this.colour = c; } public abstract double getArea(); } public class Circle extends Shape { final static double PI = ; private int radius; public Circle(int r) { radius = r; } public double getArea() { return (radius^2)*PI; }} getArea(): double setColour(int) Shape Circle If Circle did not implement getArea() then it would have to be declared abstract too! Abstract methods have no body

7 7 © S. Uchitel, 2004 Abstract Classes What are the differences between both examples? What are the differences between both examples? In Example 1 In Example 1  I choose to declare Student abstract because I think it is convenient to prevent the existence of plain Students In Example 2 In Example 2  I must declare Shape abstract because it lacks an implementation for getArea();

8 8 © S. Uchitel, 2004 Using abstract classes Class Shape cannot be instantiated (it provides a partial implementation) Class Shape cannot be instantiated (it provides a partial implementation) Abstract methods can be called on an object of apparent type Shape (they are provided by Circle ) (Polymorphism) Abstract methods can be called on an object of apparent type Shape (they are provided by Circle ) (Polymorphism) // Shape s = new Shape(); // ERROR Shape s = new Circle(4); // Ok double area = s.getArea(); // Ok – Remember polymorphism? Circle c = new Circle(3); // Ok c.setColour(GREEN); // Ok area = c.getArea(); // Ok

9 9 © S. Uchitel, 2004 Interfaces An interface is a set of methods and constants that is identified with a name. An interface is a set of methods and constants that is identified with a name. They are similar to abstract classes They are similar to abstract classes  You cannot instantiate interfaces  An interface introduces types  But, they are completely abstract (no implementation) Classes and abstract classes realize or implement interfaces. Classes and abstract classes realize or implement interfaces.  They must have (at least) all the methods and constants of the interface with public visibility interface Clock setTime(Time):void MIDNIGHT:Time

10 10 © S. Uchitel, 2004 Example: Clock Interface interface Clock { Time MIDNIGHT = new Time(0, 0, 0); Time MIDNIGHT = new Time(0, 0, 0); void setTime(Time t); void setTime(Time t);} class DigitalClock implements Clock { private Time currentTime; private Time currentTime; public DigitalClock() {reset();} public DigitalClock() {reset();} public void setTime(Time t) {currentTime = new Time(t);} public void setTime(Time t) {currentTime = new Time(t);} public void reset() {setTime(MIDNIGHT);} public void reset() {setTime(MIDNIGHT);}} interface Clock setTime(Time):void MIDNIGHT:Time DigitalClock reset():void fields are implicitly declared public static Why not do “currentTime = t;” instead of currentTime = new Time(t);” “currentTime = new Time(t);”? methods are implicitly declared public

11 11 © S. Uchitel, 2004 Interface Hierarchies Interfaces can extend each other Interfaces can extend each other interface Clock { Time MIDNIGHT = new Time(0, 0, 0); Time MIDNIGHT = new Time(0, 0, 0); void setTime(Time t); void setTime(Time t);} interface AlarmClock extends Clock { void setAlarm(Time t, Wakeable w); void setAlarm(Time t, Wakeable w);} interface Clock setTime(Time):void MIDNIGHT:Time interface AlarmClock +setAlarm(Time, Wakeable):void interface Wakeable +wake()

12 12 © S. Uchitel, 2004 Why use Interfaces? To separate (decouple) the specification available to the user from implementation To separate (decouple) the specification available to the user from implementation  I can use any class that implements the interface through the interface type (i.e. polymorphism) As a partial solution to Java’s lack of multiple inheritance As a partial solution to Java’s lack of multiple inheritance user uses interface { … } realised (implemented) class

13 13 © S. Uchitel, 2004 Decoupling: Alarm Clock Example (1/3) DigitalClock reset():void AnalogueClock interface Clock setTime(Time):void MIDNIGHT:Time interface AlarmClock +setAlarm(Time, Wakeable):void interface Wakeable +wake()

14 14 © S. Uchitel, 2004 Decoupling: Alarm Clock Example (2/3) class Sleeper implements Wakeable { private boolean sleeping; public Sleeper() { sleeping = false; } public void sleep() { if (!sleeping) { sleeping = true; System.out.println(“Yawn… Time for a nap!…Zzzz…”); }} public void wake() { if (sleeping) { sleeping = false; System.out.println(“What? Is it time to wake up?”); }} public boolean sleeping() { return sleeping; }} interface Wakeable +wake() Sleeper +sleep(Time) interface Wakeable { void wake(); }

15 15 © S. Uchitel, 2004 Decoupling: Alarm Clock Example (3/3) public static void main(String [] args) { AlarmClock a = new DigitalClock(); AlarmClock b = new AnalogueClock(); Sleeper me = new Sleeper(); Sleeper programmingIIClass = new Sleeper(); me.sleep(); programmingIIClass.sleep(); programmingIIClass.sleep(); a.setAlarm(new Time(7, 0, 0), me); //Wake up at 7am, //plenty of time before //lecture b.setAlarm(new Time(10, 50, 0), programmingIIClass); //Wake up just before //end of lecture } Polymorphism at work. Using a digital clock as in implementation for AlarmClock interface Wakeable +wake() Sleeper +sleep(Time)

16 16 © S. Uchitel, 2004 Multiple Inheritance start() stop() MultiFunctionWatch setTime() setAlarm() StopWatch AlarmClock Java does not support multiple inheritance, but...

17 17 © S. Uchitel, 2004 Multiple Interfaces Classes are allowed to implement multiple interfaces Classes are allowed to implement multiple interfaces interface StopWatch +start() +stop(): interface AlarmClock +setTime() +setAlarm(): MultiFunctionWatch Q: Why is this not the same as multiple inheritance? A: There is no implementation to inherit

18 18 © S. Uchitel, 2004 Conflict resolution rules Classes can implement multiple interfaces Classes can implement multiple interfaces Name conflict resolution: Name conflict resolution: different signatures: overloading different signatures: overloading same signature and return type: same method same signature and return type: same method same signature and different return type: compile error same signature and different return type: compile error Name conflicts: multiple methods with the same name

19 19 © S. Uchitel, 2004 Abstract classes vs. Interfaces Can have data fields Can have data fields Methods may have an implementation Methods may have an implementation Classes and abstract classes extend abstract classes. Classes and abstract classes extend abstract classes. Class cannot extend multiple abstract classes Class cannot extend multiple abstract classes Substitution principle is assumed Substitution principle is assumed Can only have constants Can only have constants Methods have no implementation Methods have no implementation Classes and abstract classes implement interfaces Classes and abstract classes implement interfaces Interfaces can extend multiple interfaces Interfaces can extend multiple interfaces A class can implement multiple interfaces A class can implement multiple interfaces Substitution principle not assumed Substitution principle not assumed

20 20 © S. Uchitel, 2004 Abstract Classes or Interfaces? If there is common implementation -> AC If there is common implementation -> AC If there is no common implementation -> If there is no common implementation ->  Interfaces allow classes implementing multiple interfaces...  Abstract classes can be subsequently extended without breaking subclasses...  No clear cut decision... Let look at what the Java Standard Class Library developers do... Let look at what the Java Standard Class Library developers do...

21 21 © S. Uchitel, 2004 Collections class HashSet extends AbstractSet implements Set … { … } Extract from the Java Standard Library hierarchy for collections

22 22 © S. Uchitel, 2004 Checklist Abstract classes and methods Abstract classes and methods Concrete classes Concrete classes Interfaces Interfaces Interface Hierarchies Interface Hierarchies Multiple Inheritance Multiple Inheritance Multiple interfaces Multiple interfaces Abstract classes vs. Interfaces Abstract classes vs. Interfaces Specialisation (extends) vs. Realization (implements) Specialisation (extends) vs. Realization (implements)


Download ppt "04 - Abstract Classes and Interfaces. 2 © S. Uchitel, 2004 Abstract Classes Unlike classes, these cannot be instantiated. Unlike classes, these cannot."

Similar presentations


Ads by Google