Comp1004: Object Oriented Design I Abstract Classes and Interfaces.

Slides:



Advertisements
Similar presentations
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Advertisements

Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
CS 106 Introduction to Computer Science I 11 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
LECTURE 07 Programming using C# Inheritance
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,
Polymorphism & Interfaces
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
CSC 142 O 1 CSC 142 Java More About Inheritance & Interfaces [Reading: chapter 13]
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Specialization and Inheritance Chapter 8. 8 Specialization Specialized classes inherit the properties and methods of the parent or base class. A dog is.
What is inheritance? It is the ability to create a new class from an existing class.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritence Put classes into a hierarchy derive a new class based on an existing class with modifications or extensions. Avoiding duplication and redundancy.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Inheritance in the Java programming language J. W. Rider.
These materials where developed by Martin Schray. Please feel free to use and modify them for non-commercial purposes. If you find them useful or would.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
C# G 1 CSC 298 Object Oriented Programming Part 2.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Object Oriented Programming
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
JAVA Programming (Session 4) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Interfaces and Polymorphism CS 162 (Summer 2009).
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
(c) University of Washington05-1 CSC 143 Java Abstract Classes and Frameworks Reading: Ch. 11.
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
BY:- TOPS Technologies
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Coming up A quick word about abstract How a class interfaces
Modern Programming Tools And Techniques-I
Sections Inheritance and Abstract Classes
Lecture 12 Inheritance.
University of Central Florida COP 3330 Object Oriented Programming
Interfaces.
Inheritance and Polymorphism
Week 6 Object-Oriented Programming (2): Polymorphism
Inheritance Inheritance is a fundamental Object Oriented concept
More About Inheritance & Interfaces
Java Inheritance.
Interfaces and Abstract Classes
Chapter 9 Carrano Chapter 10 Small Java
Chapter 14 Abstract Classes and Interfaces
Inheritance and Polymorphism
Chapter 11 Inheritance and Encapsulation and Polymorphism
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Presentation transcript:

Comp1004: Object Oriented Design I Abstract Classes and Interfaces

Coming up Abstract Classes and Methods The Challenges of Object Oriented Design – Pets vs. Animals Multiple Inheritance vs. Interfaces

Abstract Classes and Methods

Designing for Polymorphism ArrayList brokers; Brokers = new ArrayList (); brokers.add(new brokers.add(new brokers.add(new SMSBroker(“ ”)); brokers.add(new SnailBroker(“1600 Penns Ave. D.C.”)); brokers.add(new SMSBroker(“ ”)); String message = “Reminder. Fix economy!”); for(Broker b : brokers) { b.sendMsg(message); } Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg

Designing for Polymorphism Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg A design that takes advantage of Polymorphism – but there is something odd going on. Think about the constructors…

Designing for Polymorphism Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg A design that takes advantage of Polymorphism – but there is something odd going on. Think about the constructors… public class Broker { String ; //code omittted public Broker(String addr) { = addr; } public class SMSBroker extends Broker { String number; //code omittted public SMSBroker(String phoneno) { super(“Doesn’t matter – this is not used”); number = phoneno; }

Designing for Polymorphism Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg A better design would be to have a neutral Broker, and make Broker another sub-class… Broker sendMsg Now there is no redundant data in the sub-classes

Designing for Polymorphism Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg A better design would be to have a neutral Broker, and make Broker another sub-class… Broker sendMsg Now there is no redundant data in the sub-classes But what does this method do? It has to be here for Polymorphism to work. But in fact does it make sense to have an instance of a Broker at all?

Abstract Classes public abstract class Broker { public void sendMsg(String msg) { //exists so it can be //overriden in a subclass } public class SMSBroker extends Broker { String number; //code omittted public void sendMsg(String msg) { //some code to send the //msg to the phoneno } Abstract classes cannot be instantiated (i.e. created using the new keyword) They exist only to be extended A non-abstract class (the ones we normally deal with) are called concrete classes

Abstract Classes Abstract classes cannot be instantiated (i.e. created using the new keyword) They exist only to be extended A non-abstract class (the ones we normally deal with) are called concrete classes But this is still ugly – there is no guarantee that sub-classes will override this empty method! public abstract class Broker { public void sendMsg(String msg) { //exists so it can be //overriden in a subclass } public class SMSBroker extends Broker { String number; //code omittted public void sendMsg(String msg) { //some code to send the //msg to the phoneno }

Abstract Methods public abstract class Broker { public abstract void sendMsg(String msg); } public class SMSBroker extends Broker { String number; //code omittted public void sendMsg(String msg) { //some code to send the //msg to the phoneno } Abstract classes cannot be instantiated (i.e. created using the new keyword) They exist only to be extended A non-abstract class (the ones we normally deal with) are called concrete classes So we can declare sendMsg as an abstract method – this means all concrete sub-classes must override it

The point By putting abstract methods into your superclasses, you’ve guaranteed that the concrete subclasses will provide them This enables you to code for polymorphism without having to write methods that contain no code or will never be called

Abstract Summary An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: abstract void sendMsg(String msg); If a class includes abstract methods, the class itself must be declared abstract, as in: public abstract class Broker { // declare fields // declare non-abstract methods abstract void sendMsg(String msg); } When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

The Challenges of Object-Oriented Design

Back to an Animal Hierarchy AnimalCanineDogWolfFelineCatTigerRodentHamster We included methods for sleep, roam and eat in Animal In some subclasses these were overridden

Re-using this code What if we wanted to reuse this code to model someone’s pets? We want to implement some new stroke() methods, feedTreat() methods and some play() methods. How should we do this?

In groups of no more than four… Come up with some places in the hierarchy that we could add those methods to the appropriate animals. Think about using abstract methods in some cases Come up with the good points and the drawbacks for each location AnimalCanineDogWolfFelineCatTigerRodentHamster Add methods for stroke, feedTreat and play

Where could the play() method go? AnimalCanineDogWolfFelineCatTigerRodentHamster

Option 1 All animals inherit behaviour, no need to touch subclasses But what does it mean to play with an Animal? Surely we would play differently with a Dog than a Hamster? AnimalCanineDogWolfFelineCatTigerRodentHamster Put methods in Animal class

Option 2 All animals inherit behaviour, they implement their own version at the first concrete subclass But does it make sense to play will all types of Animal? It doesn’t sound very safe to play with a Tiger! AnimalCanineDogWolfFelineCatTigerRodentHamster Put methods in Animal class but mark them as abstract

Option 3 Only animals you want to have the methods will have them You can’t use Polymorphism at all – as no superclasses have the play method So you’d have to write specific code for each subtype of Animal that you could play with AnimalCanineDogWolfFelineCatTigerRodentHamster Put methods in only the classes that need the behaviour

Any other ideas? Make your suggestions What can we do to solve this?

New Pet Class It sounds like we need a separate super class: AnimalCanineDogWolfFelineCatTigerRodentHamster Pet

Multiple Inheritance vs. Interfaces

Multiple inheritance In Java, multiple inheritance is not allowed This is because it gets hard to resolve clashes Class A Class B foo() Class B foo() Class C foo() Class C foo() Class D If foo() is called on an object of type D, which method gets called?

Interfaces Java provides Interfaces to allow you to solve this problem without introducing any of the awkward questions about clashing methods An Interface behaves like a 100% abstract class – i.e. containing only abstract methods A Class can only extend one other Class, but it can implement many Interfaces An Interface is like a contract, any class that implements that Interface guarantees to provide code for its methods

public interface Pet{ void play(); } public class Dog extends Canine implements Pet { //code omitted public void play(){ System.out.println(“Dog plays with a ball”); } public class Cat extends Feline implements Pet { //code omitted public void play(){ System.out.println(“Cat plays with some string”); } public class Hamster extends Rodent implements Pet { //code omitted public void play(){ System.out.println(“Hamster plays on its wheel”); } The interface declaration looks very like a class. All methods are automatically public and abstract Remember that each class can extend only one superclass, but can implement many interfaces

public void playWithAnyTwoPets(Pet petOne, Pet petTwo){ System.out.println(“Lets play with our pets”); petOne.play(); petTwo.play(); } public static void main(String [ ] args) { Dog dog = new Dog(“Fido”); Cat cat = new Cat(“Mr Tiddles”); Hamster hamster = new Hamster(“Hammy”); playWithAnyTwoPets(dog, cat); playWithAnyTwoPets(cat, hamster); playWithAnyTwoPets(hamster, dog); } Elsewhere in our code we can use interfaces anywhere where we might use a class Here it is used as a parameter – so this method will accept any class that implements the Pet interface We cannot create an instance of a Pet, however we can create instances of classes that implement Pet And pass them as a parameter when a Pet is expected (just like passing a subclass when a superclass is expected)

Extend vs. Implements Extend means to add additional behaviour or data (methods or member variables) Implements means to provide implementation for a set of methods A Class can extend one other class A Class can implement many Interfaces

Extend vs. Implements Extend means to add additional behaviour or data (methods or member variables) Implements means to provide implementation for a set of methods A Class can extend one other class A Class can implement many Interfaces An Interface can also extend many other Interfaces!

public interface Pet { void play(); } public interface CagedPet extends Pet { void takeOutOfCage(); void putInCage(); } public class Hamster extends Rodent implements CagedPet { //code omitted private boolean inCage = true; public void play() { if(inCage) System.out.println(“Hamster plays on its wheel”); else System.out.println(“Hamster trundles in its ball”); } public void takeOutOfCage() { inCage = false; } public void putInCage () { inCage = true; } Here CagedPet extends Pet which means that classes that implement CagedPet must provide all three methods Each class that implements CagedPet is free to implement those methods however it sees fit

Summary Abstract Classes and Methods The Challenges of Object Oriented Design – Pets vs. Animals Multiple Inheritance vs. Interfaces