Abstract Classes and Interfaces

Similar documents
The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Java Fundamentals (II)

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Java Magistère BFA

Super-Classes and sub-classes

public Candy() { ingredients = new ArrayList<String>(); ingredients.add("sugar");

INHERITANCE. Spring 2019

Polymorphism. return a.doublevalue() + b.doublevalue();

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

C12a: The Object Superclass and Selected Methods

JAVA MOCK TEST JAVA MOCK TEST II

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance (Part 5) Odds and ends

The class Object. Lecture CS1122 Summer 2008

Java Object Oriented Design. CSC207 Fall 2014

Distributed Systems Recitation 1. Tamim Jabban

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

What is Inheritance?

COE318 Lecture Notes Week 8 (Oct 24, 2011)

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

Rules and syntax for inheritance. The boring stuff

Inheritance. The Java Platform Class Hierarchy

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Introduction to Programming Using Java (98-388)

Lecture 4: Extending Classes. Concept

Distributed Systems Recitation 1. Tamim Jabban

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Chapter 13 Abstract Classes and Interfaces

Java Classes, Inheritance, and Interfaces

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Programming Languages and Techniques (CIS120)

CISC370: Inheritance

CMSC 132: Object-Oriented Programming II

More On inheritance. What you can do in subclass regarding methods:

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

java.lang.object: Equality

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Chapter 14 Abstract Classes and Interfaces

Inheritance. Transitivity

More about inheritance

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

CS-202 Introduction to Object Oriented Programming

Object-Oriented Concepts

Methods Common to all Classes

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Fundamental Java Methods

Inheritance (Outsource: )

Polymorphism and Interfaces. CGS 3416 Spring 2018

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

INTERFACE WHY INTERFACE

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Java Enum Java, winter semester ,2018 1

Inheritance (continued) Inheritance

Binghamton University. CS-140 Fall Chapter 9. Inheritance

Programming II (CS300)

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

CLASS DESIGN. Objectives MODULE 4

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

Implements vs. Extends When Defining a Class

CS 251 Intermediate Programming Inheritance

Lecture 18 CSE11 Fall 2013 Inheritance

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

1 Shyam sir JAVA Notes

AP CS Unit 6: Inheritance Notes

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CSC9T4: Object Modelling, principles of OO design and implementation

Computer Science II (20073) Week 1: Review and Inheritance

Inheritance and Polymorphism

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

More Relationships Between Classes

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp

CS260 Intro to Java & Android 03.Java Language Basics

COMP 401 COPY: SHALLOW AND DEEP. Instructor: Prasun Dewan

Objects and Iterators

Transcription:

Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass to hold common code and declare abstract behavior Want a class with common code (to reduce redundancy) but the class should never be instantiated (doesn t make sense in context of program) Abstract methods: declared but not implemented this is behavior that you promise to implement when you implement the interface If every subclass of a superclass would override a particular method, consider making it abstract CSC216: Programming Concepts Sarah Heckman 2 1

A Deeper Look at Beer Beer is a very general name for lots of different types of beverages Beers fall into two high level categories Ales: top fermenting yeast with fermentation range around room temp Lagers: bottom fermenting yeast with fermentation range between 46 59 F Ales and Lagers would add different types of ingredients particularly yeast CSC216: Programming Concepts Sarah Heckman 3 Beer Hierarchy CSC216: Programming Concepts Sarah Heckman 4 2

Beer Class Make the addingredient() method abstract Why? Ales and Lagers will each require different ingredients Ales and Lagers may also want to store their ingredients in different data structures CSC216: Programming Concepts Sarah Heckman 5 Beer Class (Abstract) public abstract class Beer { private String name; public Beer(String name) { this.name = name; public abstract boolean addingredient(beeringredient i); public String getname() { return name; CSC216: Programming Concepts Sarah Heckman 6 3

Abstract Classes Any class with abstract methods must be declared abstract in class header Abstract classes can have constructors to initialize its state Concrete classes should call those constructors to maintain paradigm of one path of construction Cannot create instances of classes that are abstract Beer b = new Beer( Pale Ale ); //legal? Classes without abstract methods can still be abstract Make classes abstract when you don t want them instantiated Concrete methods in abstract classes may call abstract methods, even if there is no implementation of the abstract method in the file. Concrete subclass is required to implement the abstract methods Can only call superclass method if there is an instantiated concrete object with the overridden methods! Document like concrete classes Javadoc! CSC216: Programming Concepts Sarah Heckman 7 Ale Implementation (Concrete) public class Ale extends Beer { private ArrayList<BeerIngredient> ingredients; public Ale(String name) { super(name); ingredients = new ArrayList<BeerIngredient>(); public boolean addingredient(beeringredient i) { if (i instanceof Yeast) { Yeast y = (Yeast)i; //Check to see if yeast s fermentation range is that //required for an ale, add (if appropriate) //and return appropriate value else { ingredients.add(i); return true; CSC216: Programming Concepts Sarah Heckman 8 4

Concrete Classes Concrete classes extend abstract classes and must implement abstract methods Single inheritance still applies for the concrete classes Concrete class constructors still call one of the superclass constructors Pass appropriate parameters to superclass constructor to initialize superclass state If no explicit call to a superclass constructor, try to go through the parameterless constructor CSC216: Programming Concepts Sarah Heckman 9 Heckman Brewery public class BeerMain { public static void main(string [] args) { ArrayList<Beer> beersontap = new ArrayList<Beer>(); beersontap.add(new Ale( Pale Ale )); beersontap.add(new Lager( Pilsener )); Yeast y = new Yeast( British Ale Liquid Yeast, 125, 0, null, 70, 85); for (int i = 0; i < beersontap.size(); i++) { //Which line is printed for each Beer? if (beersontap.get(i).addingredient(y)) { System.out.println( Yeast added to + beersontap.get(i).getname()); else { System.out.println( Yeast NOT added to + beersontap.get(i).getname()); CSC216: Programming Concepts Sarah Heckman 10 5

Pros and Cons of Abstract Classes Pros Contains both concrete and abstract methods Allows for common code Provide common interface for functionality that all child classes should override Guarantees functionality of abstract method(s) will exist when overridden Allow for polymorphism Cons Concrete classes can only extend one class (even if the extended class is abstract) CSC216: Programming Concepts Sarah Heckman 11 Drawbacks of Inheritance Java uses single inheritance A class can only extend ONE class (only have ONE superclass) Single inheritance prevents ambiguity if two parent classes share the same method signature(s) Can t set up multiple is a relationships What if we want an is a relationship without sharing code? We want to guarantee shared functionality of objects that are the same thing, but we don t care about the implementation of the functionality. CSC216: Programming Concepts Sarah Heckman 12 6

Interfaces A set of methods that classes can promise to implement, allowing you to treat those classes similarly in your code An interface is a contract that a subclass MUST have the listed behaviors If an object implements an interface, the object has certain known behavior Still can take advantage of polymorphism Classes can implement multiple interfaces CSC216: Programming Concepts Sarah Heckman 13 Interfaces (2) Interfaces define what something can do A class defines what something is Example Interfaces Runnable: threads Comparable: ordering and comparing objects Observable: responding to UI events Serializable: objects are saved to files List, Set, Map, and Iterator: data structures CSC216: Programming Concepts Sarah Heckman 14 7

What are things Beer can do? What are the adjectives associated with Beer? Drinkable Brewable Fermentable CSC216: Programming Concepts Sarah Heckman 15 Beer Class Diagram Revised CSC216: Programming Concepts Sarah Heckman 16 8

Brewable Interface /** * Interface for objects that can be brewed * @author Sarah Heckman */ public interface Brewable { /** * Brew the object */ void brew(); CSC216: Programming Concepts Sarah Heckman 17 Interfaces Declared with keyword interface Only method signatures no method code! Methods are automatically abstract Don t need to use public on methods all interface methods automatically public Interface methods cannot be static Data members are public, static, and final (constants) No constructors Document with Javadoc! CSC216: Programming Concepts Sarah Heckman 18 9

Revised Beer Class public abstract class Beer implements Brewable, Fermentable { private String name; public abstract boolean addingredient(beeringredient i); public String getname() { return name; public String setname(string name) { this.name = name; public void brew() { //order ingredients by add time (descending) //and brew a delicious beverage! System.out.println( I m brewing!! ); public void ferment() { System.out.println( I m fermenting!! ); CSC216: Programming Concepts Sarah Heckman 19 Interfaces Interfaces can be used with other things not in the Beer hierarchy What else can you brew? CSC216: Programming Concepts Sarah Heckman 20 10

Interfaces and Abstract Classes Abstract classes (like Beer) can implement interfaces which means all child classes automatically inherit the interface behaviors Even better, you can choose NOT to implement the abstract method from the interface Requires that the concrete child of the abstract class MUST implement the interface s behavior CSC216: Programming Concepts Sarah Heckman 21 Heckman Brewery Revisited public class HeckmanBrewery { public static void main(string [] args) { ArrayList<Beer> beersontap = new ArrayList<Beer>(); beersontap.add(new Ale( Pale Ale )); beersontap.add(new Lager( Pilsener )); for (int i = 0; i < beersontap.size(); i++) { //add ingredients beersontap.get(i).brew(); CSC216: Programming Concepts Sarah Heckman 22 11

Benefits of Interfaces Implementing a common interface provides a type hierarchy similar to inheritance Smart, uniform design Use to achieve polymorphism All Beers have a common set of functionality Brewable Fermentable Example of additive not invasive Bi pass limitations of single inheritance Specifies behaviors you want your class to have! Think something able CSC216: Programming Concepts Sarah Heckman 23 The Object Methods and Inheritance Object is a (direct or indirect) superclass of all Java classes Method String tostring() boolean equals(object obj) int hashcode() protected Object clone() Class<?> getclass() Purpose Returns a String representation of the object. Indicates whether some other object is equal to this one. Returns a hash code value for the object. Creates and returns a copy of this object. Returns the runtime class of this Object CSC216: Programming Concepts Sarah Heckman 24 12

Generalizing tostring() in Superclasses To make tostring() useful by subclasses public String tostring() { return getclass().getname() + //info on fields; getclass() is a method of Object that returns a Class object. The getname() method returns the name of the class. The tostring() on a child class should also be overridden to include info on the child s fields use super.tostring() to access the parent. CSC216: Programming Concepts Sarah Heckman 25 equals() and hashcode() with Inheritance Always handle the superclass first! public class FlavoredBeerIngredient { public boolean equals(object o) { //Test the superclass for equality first! if (!super.equals(o)) return false; if (getclass()!= o.getclass()) return false; FlavoredBeerIngredient f = (FlavoredBeerIngredient)o; //test fields CSC216: Programming Concepts Sarah Heckman 26 13

The clone() method Use the clone() method if you want to make a copy of an object Because copying an object reference gives you two references to the SAME under lying object clone() returns a new (as in stored in a different location) object that has identical state to the existing object clone() creates a shallow copy object fields are references to the objects not new copies of the objects Must override clone() to create a deep copy clone() returns an object of type Object Must cast to the type of object you want Hops h = (Hops) oldhops.clone(); Could potentially lead to ClassCastExceptions CSC216: Programming Concepts Sarah Heckman 27 Immutable Objects and clone() Use the clone() method to make copies of mutable objects in accessor methods of classes Prevents the breaking of encapsulation public class FlavoredBeerIngredient { private ArrayList<String> flavors; public ArrayList<String> getflavors() { return (ArrayList<String>)flavors.clone(); CSC216: Programming Concepts Sarah Heckman 28 14

Overriding clone() The Object class implementation of clone() has safeguards clone() is protected so can t be called accidently Implementation of clone() must be public Class must be an instance of Cloneable Must catch CloneNotSupportedException If you want a deep copy, then object references must be cloned as well Object.clone() does the right thing for primitives CSC216: Programming Concepts Sarah Heckman 29 clone() Example public class FlavoredBeerIngredient implements Cloneable { public Object clone() { try { FlavoredBeerIngredient cloned = (FlavoredBeerIngredient) super.clone(); cloned.flavors = (ArrayList<String>) flavors.clone(); return cloned; catch (CloneNotSupportedException e) { //Always have to catch, even if implement Cloneable return null; CSC216: Programming Concepts Sarah Heckman 30 15

References Dr. Jo Perry s lecture notes CSC216: Programming Concepts Sarah Heckman 31 16