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

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Object Oriented Programming with Java
Abstract Class and Interface
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Interfaces.
Inheritance Inheritance allows the derivation of a new class from an existing one, for the purpose of reuse, enhancement, adaptation, etc. superclass (a.k.a.
Abstract Classes and Interfaces The objectives of this chapter are: To explore the concept of abstract classes To understand interfaces To understand the.
Inheritance Inheritance Reserved word protected Reserved word super
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Java Interfaces Overview Java Interfaces: A Definition.
Chapter 10 Classes Continued
Object-Orientated Design and Programming Unit 9: Abstract Classes and Interfaces Jin Sa.
Abstract Classes b b An abstract class is a placeholder in a class hierarchy that represents a generic concept b b An abstract class cannot be instantiated.
Abstract Classes and Interfaces
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
Abstract classes and Interfaces. Abstract classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Lecture 3 Casting Abstract Classes and Methods Interfaces.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Programming in Java CSCI-2220 Object Oriented Programming.
Types in programming languages1 What are types, and why do we need them?
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Object Oriented Programming
Lecture 21 - Abstract Classes and Interface. Example Figure –Rectangle –Triangle Figure –Dimensions –Area.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
11 Implementing Abstract Classes. 2 Contents Define Abstract Class Rules on Abstract Class Define Interface Implementing Interface Uses of Interface Abstract.
1 Interfaces and Abstract Classes The ability to define the behavior of an object without specifying that behavior is to be implemented Interface class.
1 / 41 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 5 Programming Fundamentals using Java 1.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 7 : Interfaces King Fahd University of Petroleum & Minerals College of Computer.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Modern Programming Tools And Techniques-I
Web Design & Development Lecture 9
Sixth Lecture ArrayList Abstract Class and Interface
Inheritance and Polymorphism
EKT 472: Object Oriented Programming
Interface.
More inheritance, Abstract Classes and Interfaces
Chapter 9 Carrano Chapter 10 Small Java
Chapter 14 Abstract Classes and Interfaces
Abstract Classes and Interfaces
Final and Abstract Classes
Abstract Classes and Interfaces
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

04 - Abstract Classes and Interfaces

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 © 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 © 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 © 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 © 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 © 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 © 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 © 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 © 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 © 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 © 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 © 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 © 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 © 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 © S. Uchitel, 2004 Multiple Inheritance start() stop() MultiFunctionWatch setTime() setAlarm() StopWatch AlarmClock Java does not support multiple inheritance, but...

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 © 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 © 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 © 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 © S. Uchitel, 2004 Collections class HashSet extends AbstractSet implements Set … { … } Extract from the Java Standard Library hierarchy for collections

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)