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

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

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

Chapter 13 Abstract Classes and Interfaces

Motivations. Chapter 13 Abstract Classes and Interfaces

Chapter 13 Abstract Classes and Interfaces

Chapter 13 Abstract Classes and Interfaces

Chapter 9 Abstract Classes and Interfaces

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

C20a: Selected Interfaces in Java API

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

We are on the GUI fast track path

Abstract Classes Interfaces

Chapter 14 Abstract Classes and Interfaces

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

CS-202 Introduction to Object Oriented Programming

Object Oriented System Development Paradigm. Sunnie Chung CIS433 System Analysis Methods

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

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

Inheritance and Interfaces

Java Object Oriented Design. CSC207 Fall 2014

CS1150 Principles of Computer Science Objects and Classes

What is an interface? Why is an interface useful?

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Interface Class. Lecture 22. Based on Slides of Dr. Norazah Yusof

CS171:Introduction to Computer Science II. Li Xiong

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

25. Generic Programming

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Inheritance, Polymorphism, and Interfaces

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Inheritance (continued) Inheritance

Chapter 6 Introduction to Defining Classes

Programming II (CS300)

INHERITANCE. Spring 2019

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance and Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

CST141 Thinking in Objects Page 1

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

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

Abstract Classes and Interfaces

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

What is Inheritance?

Programming overview

For this section, we will implement a class with only non-static features, that represents a rectangle

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Inheritance and Interfaces

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

ITI Introduction to Computing II

COP 3330 Final Exam Review

Inheritance and Polymorphism

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

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

Programming II (CS300)

CS 251 Intermediate Programming Inheritance

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Final Examination Semester 3 / Year 2010

CO Java SE 8: Fundamentals

ITI Introduction to Computing II

15CS45 : OBJECT ORIENTED CONCEPTS

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

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Index COPYRIGHTED MATERIAL

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS1004: Intro to CS in Java, Spring 2005

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

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Chapter 4 Defining Classes I

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Polymorphism and Interfaces. CGS 3416 Spring 2018

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

CMSC 132: Object-Oriented Programming II

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Questions Answer Key Questions Answer Key Questions Answer Key

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

CISC370: Inheritance

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

Programming Exercise 14: Inheritance and Polymorphism

Practice for Chapter 11

Ryerson University Department of Electrical & Computer Engineering COE618 Midterm Examination February 26, 2013

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

CMSC 132: Object-Oriented Programming II

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

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Transcription:

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

Motivations We have learned how to write simple programs to create and display GUI components. Can we write the code to respond to user actions, such as clicking a button to perform an action? In order to write such code, we have to know about interfaces. An interface is for defining common behavior for classes (including unrelated classes). Before discussing interfaces, we introduce a closely related subject: abstract classes. 3 Objectives To design and use abstract classes ( 13.2). To generalize numeric wrapper classes, BigInteger, and BigDecimal using the abstract Number class ( 13.3). To process a calendar using the Calendar and GregorianCalendar classes ( 13.4). To specify common behavior for objects using interfaces ( 13.5). To define interfaces and define classes that implement interfaces ( 13.5). To define a natural order using the Comparable interface ( 13.6). To make objects cloneable using the Cloneable interface ( 13.7). To explore the similarities and differences among concrete classes, abstract classes, and interfaces ( 13.8). To design the Rational class for processing rational numbers ( 13.9). To design classes that follow the class-design guidelines ( 13.10). 4 2

Abstract Classes & Abstract Methods An abstract class is a class that is declared abstract Abstract classes cannot be instantiated, but they can be subclassed Abstract methods are declared when their implementations are dependent on the subclasses where they are invoked, e.g. getarea() in GeometricObject Abstract methods are non-static methods that are declared without implementations (without {, but followed by a ;): public abstract class Account { // declare data fields // declare concrete methods abstract void check(double balance); 5 Abstract Classes & Abstract Methods GeometricObject Circle Rectangle TestGeometricObject 6 Run 3

Abstract Classes & Abstract Methods In a concrete subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined abstract An abstract class may contain just concrete methods, or just abstract methods, or both or none! A concrete class cannot contain abstract methods 7 Abstract Classes A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract We cannot create an instance from an abstract class using the new operator, but: We can include constructors (to be used by subclasses) in an abstract class An abstract class can be used as a data type. For example, the following statement, which creates an array whose elements are of abstract class GeometricObject type, is correct GeometricObject[] geo = new GeometricObject[10]; 8 4

Case Study: Abstract Number Class LargestNumbers Run 9 Abstract Calendar Class & its Concrete GregorianCalendar Subclass 10 5

Abstract Calendar Class & its Concrete GregorianCalendar Subclass An instance of java.util.date represents a specific instant in time with millisecond precision java.util.calendar is an abstract base class for extracting detailed information such as year, month, date, hour, minute and second from a Date object Subclasses of Calendar can implement specific calendar systems such as Gregorian calendar, Lunar Calendar and Jewish calendar Currently, java.util.gregoriancalendar for the Gregorian calendar is supported in the Java API 11 The GregorianCalendar Concrete Class We can use new GregorianCalendar() to construct a default GregorianCalendar object with the current time We can also use new GregorianCalendar(year, month, date) to construct a GregorianCalendar object with the specified year, month, and date The month parameter is 0-based, i.e., 0 is for January 12 6

get() in Calendar Class get(int field) is used to extract detailed information from Calendar objects. The possible fields are: TestCalendar Run 13 Interfaces The Apple & Chicken classes are based on different superclasses, but both share a common behavior: both are edible! We can model this common behavior using an interface Interfaces can be used to specify common behavior for objects of unrelated classes as well as related classes Abstract classes model the common behavior of related classes only 14 7

interface & class Similarities An interface is treated like a special class in Java Each interface is compiled into a separate bytecode file, just like a regular class Like an abstract class, we cannot create an instance from an interface using the new operator, but in most cases we can use an interface more or less the same way we use an abstract class For example, we can use an interface as a data type and cast a variable of an interface type to its subclass, and vice versa 15 Defining an interface An interface is a class-like construct that contains only constants and abstract methods public interface InterfaceName { constant declarations; abstract method signatures; Example: public interface Edible { /** Describe how to eat */ public abstract String howtoeat(); 16 8

interface inheritance We can use the Edible interface to specify whether an object is edible. This is accomplished by letting the class for the object implement this interface (or inherit the interface) using the implements keyword Example: Chicken & Fruit implement the Edible interface in TestEdible Edible TestEdible Run 17 Omitting Modifiers in Interfaces All data fields are public final static and all methods are public abstract in an interface. For this reason, these modifiers can be omitted, as shown below: public interface T1 { public static final int K = 1; Equivalent public interface T1 { int K = 1; public abstract void p(); void p(); A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K) 18 9

Example: The Comparable Interface This interface defines compareto() for comparing objects compareto() determines the order of this object with the specified object o and returns a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than o package java.lang; public interface Comparable<E> { public int compareto(e o); 19 compareto() in Integer, BigInteger, String & Date All numeric wrapper classes, Character and String implement Comparable, thus compareto() is implemented in all of them public class Integer extends Number implements Comparable<Integer> { // class body omitted @Override public int compareto(integer o) { // Implementation omitted public class BigInteger extends Number implements Comparable<BigInteger> { // class body omitted @Override public int compareto(biginteger o) { // Implementation omitted public class String extends Object implements Comparable<String> { // class body omitted @Override public int compareto(string o) { // Implementation omitted public class Date extends Object implements Comparable<Date> { // class body omitted @Override public int compareto(date o) { // Implementation omitted 20 10

Example: compareto() System.out.println(new Integer(3).compareTo(new Integer(5))); System.out.println("ABC".compareTo("ABE")); java.util.date date1 = new java.util.date(2013, 1, 1); java.util.date date2 = new java.util.date(2012, 1, 1); System.out.println(date1.compareTo(date2)); Displays -1-2 1 21 The Comparable Interface Let n be an Integer object, s be a String object and d be a Date object. Then, all the following expressions are true n instanceof Integer n instanceof Object n instanceof Comparable s instanceof String s instanceof Object s instanceof Comparable d instanceof java.util.date d instanceof Object d instanceof Comparable 22 11

CS 112 Programming 2 Lecture 11 Abstract Classes & Interfaces (2) First Midterm Exam Monday, 29 February (same time as the lecture) 75 minute duration Will cover all lectures delivered before the exam date Will consist of MCQ s, fill-in-the-blanks, questions with short answers, programming tasks, and drawing of diagrams If you miss this exam for any reason, you will have to appear for a makeup exam on the Thursday of the last week of teaching (5 May). That exam will cover al lectures delivered in the semester. It will consist of programming tasks, drawing of diagrams and answering questions having 0.5-1 page answers 12

Generic sort() java.util.arrays.sort(array) requires that the elements in an array implement the Comparable<E> interface SortComparableObjects Run 25 Defining Classes to Implement Comparable We cannot use sort() to sort an array of Rectangle objects, because Rectangle does not implement Comparable However, we can define a new rectangle class that implements Comparable. The instances of this new class are comparable ComparableRectangle SortRectangles Run 26 13

The Cloneable Interface The Cloneable interface specifies that an object can be cloned A class that implements the Cloneable interface is marked cloneable, and its objects can be cloned using clone() defined in the Object class. clone() returns the copy of an object package java.lang; public interface Cloneable { Cloneable is a marker interface, an empty interface A marker interface does not contain constants or methods It is used to denote that a class possesses certain desirable properties 27 Example: Cloneable Several classes (e.g., Date, Calendar and ArrayList) in the Java library implement Cloneable. Thus, the instances of these classes can be cloned. For example, the following code: Calendar calendar = new GregorianCalendar(2003, 2, 1); Calendar calendarcopy = (Calendar)calendar.clone(); System.out.println("calendar == calendarcopy is " + (calendar == calendarcopy)); System.out.println("calendar.equals(calendarCopy) is " + calendar.equals(calendarcopy)); displays calendar == calendarcopy is false calendar.equals(calendarcopy) is true 28 14

Implementing Cloneable Interface To define a custom class that implements the Cloneable interface, the class must override clone() in Object The following code defines a class named House that implements Cloneable and Comparable House 29 Shallow vs. Deep Copy House house1 = new House(1, 1750.50); House house2 = (House)house1.clone(); If object A is copied as object B then if any properties of A are a reference to a memory location, at the end of copying the two objects will be using the same reference. The default clone() makes a shallow copy 30 15

Shallow vs. Deep Copy House house1 = new House(1, 1750.50); House house2 = (House)house1.clone(); Instead of references, if the actual values are copied to a new object then that will be a deep copy. This way the two objects are completely independent. To make a deep copy, we need to override the default clone() 31 Interfaces vs. Abstract Classes Abstract class Interface Variables Constructors Methods No restrictions Must be public static final Constructors are invoked by subclasses through constructor chaining. An abstract class cannot be instantiated using the new operator No constructors. An interface cannot be instantiated using the new operator No restrictions (abstract methods can t be static) Must be public abstract (abstract methods can t be static) 32 16

Interfaces All classes share a single root (Object). There is no single root for interfaces A variable of an interface type can reference any instance of the class that implements that interface Sub-interfaces: public interface infb extends infa { If c is an instance of Class2, c is also an instance of Object, Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2 33 The Rational Class Rational TestRationalClass 34 Run 17

Class Design Guidelines: Coherence A class should describe a single entity, and all the class operations should logically fit together to support a coherent purpose We can use a class for students, for example, but we should not combine students and staff in the same class, because students and staff are different entities A single entity with many responsibilities should be broken into several classes to separate the responsibilities The classes String, StringBuilder, and StringBuffer all deal with strings, for example, but have different responsibilities: String deals with immutable strings StringBuilder deals with mutable strings StringBuffer is similar to StringBuilder except that it contains synchronized methods that are required for threaded applications 35 Class Design Guidelines: Consistency Follow standard Java programming style and naming conventions Choose informative names for classes, data fields, and methods Place the data declaration before the constructor and place constructors before methods Make the names consistent. For example, length() returns the size of a String, StringBuilder, or StringBuffer. It would not be consistent if different names were used for this method in these classes Provide a public no-arg constructor for constructing an instance If a class does not support a no-arg constructor, document the reason If no constructors are defined explicitly, a public no-arg constructor with an empty body is assumed Override equals(), hashcode() and tostring() defined in the Object class whenever possible 36 18

Class Design Guidelines: Encapsulation A class should use the private modifier to hide its data from direct access by clients. This makes the class easy to maintain Provide accessors and mutators only if necessary Example: The Rational class provides accessors for numerator and denominator, but no mutators, because a Rational object is immutable 37 Class Design Guidelines: Clarity Cohesion, consistency, & encapsulation improve class clarity. A class should also have a clear contract that is easy to explain & understand Users should be able to use classes in many different combinations, orders, and environments. Therefore, design a class that imposes no restrictions on how or when the user can use it allows the user to set properties in any order and with any combination of values executes methods correctly independent of their order of occurrence Methods should be defined intuitively without causing confusion Example: It is more intuitive to return a substring from beginindex to endindex, instead of beginindex to endindex-1) Do not declare a data field that can be derived from other data fields (e.g. no need to store both birthdate and age) 38 19

Class Design Guidelines: Completeness Classes are designed for use by many different customers. In order to be useful in a wide range of applications, a class should provide a variety of ways for customization through properties and methods Example: The String class contains more than 40 methods that are useful for a variety of applications 39 Class Design Guidelines: Instance vs. static A variable or method that is dependent on a specific instance of the class must be an instance variable or method A variable that is shared by all the instances of a class should be declared static A method that is not dependent on a specific instance should be defined as a static method Always reference static variables and methods from a class name to improve readability and avoid errors A static variable or method can be invoked from an instance method, but an instance variable or method cannot be invoked from a static method 40 20

Class Design Guidelines: Inheritance vs. Aggregation The difference between inheritance and aggregation is the difference between an is-a and a has-a relationship An apple is a fruit; thus, we would use inheritance to model the relationship between the classes Apple and Fruit A person has a name; thus, we would use aggregation to model the relationship between the classes Person and Name 41 Class Design Guidelines: Interfaces vs. Abstract Classes Both can be used to specify common behavior. In general, a strong is-a relationship that clearly describes a parent-child relationship should be modeled using classes, e.g. orange is a fruit A weak is-a (or is-kind-of ) relationship, indicates that an object possesses a certain property. A weak is-a relationship can be modeled using interfaces, e.g. all strings are comparable, so the String class implements the Comparable interface A circle or a rectangle is a geometric object, so Circle can be designed as a subclass of GeometricObject. Circles are different and comparable based on their radii, so Circle can implement the Comparable interface A subclass can extend only one superclass but can implement any number of interfaces 42 21

Class Design Guidelines: Visibility Modifiers Each class can present two contracts one for the users of the class and one for the extenders of the class The contract for the extenders includes the contract for the users Make the fields private and accessor methods public if they are intended for the users of the class Make the fields or methods protected if they are intended for extenders of the class The extended class may increase the visibility of an instance method from protected to public, or change its implementation, but we should never change the implementation in a way that violates the contract 43 22