11. Abstract Classes and Interfaces

Size: px
Start display at page:

Download "11. Abstract Classes and Interfaces"

Transcription

1 11. Abstract Classes and Interfaces THIS SECTION IS OPTIONAL FOR CMPT 101, and you will find it was written for a different course. It refers to previous exercises that are not part of Cmpt 101. Sometimes in software development, we see or create base classes that should never be instantiated. They are present only for the purpose of localizing into one easily-maintained section of code the common attributes and functions for an whole inheritance family. This prevents them needing to be duplicated in all the subclasses. However, as a result the base class may seem somewhat artificial. There is a way in many object-oriented languages to label these so they cannot be instantiated by mistake, and so every application programmer recognizes them for what they are. They are called abstract classes or abstract base classes. Java has another feature called interfaces that are similar to abstract classes that have no attributes and not even one function body. Both abstract classes, or Java s novel interface feature, often form a base for polymorphic sections of code in Java. This is why they are both treated in this one section. C++ has multiple inheritance of class implementations, and interesting and powerful feature. However, multiple inheritance can be troublesome to program, and difficult to compile. Java interfaces and its single root Object class, can in most cases eliminate the need for multiple inheritance. Copyright Russell Tront, Page 11-1 Section Table of Contents 11. ABSTRACT CLASSES AND INTERFACES ABSTRACT CLASSES An Abstract Class Programming Example EXERCISE A INTERFACES Declaring An Interface Using an Interface and Interface Polymorphism Implementing an Interface EXERCISE B MULTIPLE INTERFACES INTERFACE CONSTANTS AND OTHER WEIRD THINGS25 Copyright Russell Tront, Page 11-2

2 11.1 Abstract Classes Sometimes we program a bunch of classes that seem to have a lot in common. So we extract that commonality and put it in a base class, from which we then extend our other classes. This is called generalization. Often generalization takes place in a more planned manner. Good OO architects will recognize commonality, even before any classes are written. Using UML class inheritance diagrams they communicate this structure to their colleagues. Sometimes though, the base class is so artificial that it will never be actually instantiated. Here is an example with which you are probably familiar. Parent/Super/ Base Class Child/Sub/ /Derived Classes Conventional desiredtemp selfcleaningnow Ovens currenttemp start( ) is-a Microwave powerlevel Generalization Specialization Barbeque valveposition settemp( ) startselfclean() setpower( ) setvalve( ) We never want to instantiate Oven object software, because there is no way to set the temperature or power of an Oven. Another example might be a base class called Aircraft in the federal government transport licensing system. There is no such thing as a generic Aircraft, only concrete classes like Airplane, Helicopter, Balloon, Hovercraft, etc. Nonetheless, all Aircraft have a license number, an owner, an address, a phone number, a date of production, etc. And functions related to these attributes. Copyright Russell Tront, Page 11-3 Copyright Russell Tront, Page 11-4

3 Such a base class is present only to provide a base of common attributes and code from which other properly useful classes will be derived. Such base classes are called abstract classes by Java programmers. The derived classes are called concrete classes (as long as they, in turn, do not also happen to be abstract). When thinking about abstract classes, note the distinctions between the abstract base class designer, concrete subclass programmers, and in addition, application programmers who may use the concrete subclasses! Each has a different role with different goals An Abstract Class Programming Example Let us consider generalizing our previous graphical object inheritance tree even higher, so that Point inherits from an abstract base class called Location. Suppose we make the abstract Location class have x and y coordinates, and no color attribute (because conceptionally, a location does not have a color). In addition, you cannot display a location. abstract class Location { protected float x_coord; protected float y_coord; public void move(float x, float y){ x_coord = x; y_coord = y; public abstract void display(); We can then derive Point from this Location class: class Point extends Location{ protected Color color; public void setcolor(color color){ this.color = color; public void display() { drawpoint(x_coord, y_coord, color); Copyright Russell Tront, Page 11-5 Copyright Russell Tront, Page 11-6

4 Notice that Point can add an attribute, add a member function, possibly override member functions, and especially notice that it adds a body to the previously abstract function display( ). Now we can also derive other things like rectangles, windows, buttons, and all sorts of other things from the abstract Location class, thus taking advantage of the already written Location code. Also, modifications to the move( ) function only need to be done in one class. These advantages are of course more useful if the code in Location contained hundreds of lines of functionality that is inherited by a number of concrete subclasses. The nature of a Location is such that you can t really display it. It is not a visible point; it is an abstract concept. (Not all abstract classes are abstract concepts; for example, the concept of an Aircraft is pretty concrete, though a bit too general for instantiation.) Usually there is something so general or abstract about an abstract class, that the author of the abstract base class cannot provide an implementation body for some function, even though she knows that every subclass will require such a function. She likely even knows what the name and parameter list should be for that function. This is often the case because that function will be used polymorphically. The code that uses the inheritance tree of classes may have already been written! So, the purpose of an abstract function is pretty well known ahead of time, but each subclass will likely have to implement it differently. Abstract functions allow the base class programmer to declare a base set of functions for a whole family of classes, without defining that family or the bodies of those functions. Every member of that family will inherit this function set. Moreover, to be instantiated, every subclass author MUST implement this function set appropriately for its type. Abstract functions thus allow the base class author to force subclass authors to program particular functions, even if the base class programmer does not know what the appropriate bodies for each subclass would be. Such functions are written in the abstract base class with no body (not even empty braces, nor C++ s =0 notation). As shown above, all that is needed is a semi-colon after the function signature. Java requires that you label member functions with no bodies abstract. Note that it is possible to have an abstract class with no abstract functions. This indicates to subclass programmers that they need to ADD some unnamed function (not just function body) to the abstract class when deriving from it. Abstract classes without an abstract function are rare. And they should be well commented as to what needs to be added. Also, note that if you have an abstract class with no function bodies (i.e. all functions are abstract), it might be more appropriate to use a Java interface instead of an abstract class. This is especially true if there are also no instance attributes in the class. We will discuss Java interfaces shortly. Copyright Russell Tront, Page 11-7 Copyright Russell Tront, Page 11-8

5 11.2 Exercise A Take the OvenC class developed as an exercise in a previous section of this course, and make the print( ) function abstract. Call the new class OvenCA. Don t forget to rename the constructors and all other references to the old OvenC. Note that in UML, abstract method names are italicized, as are names of the abstract classes that contain them. OvenCA temperature pressure percentoxygen setoven( ) print( ) static printoven( ) static main( ) function does not call the OvenCA print( ) function, because OvenCA s print( ) function is abstract and has no body! Have the OvenSA main function instantiate and print a couple of instances of OvenSA. Test run OvenSA.main( ). Next, try modifying the OvenSA main so that it uses the setoven( ) function from OvenCA. Run the program again to prove that you can inherit functional code from the nonabstract functions of an abstract parent class. Also note that you are inheriting useful attribute fields from the parent abstract class. Finally, in OvenSA s main function, try instantiating an instance of OvenCA. Will this compile? Will this run? OvenSA percenthumidity print( ) static main( ) Convert the OvenS subclass developed as an exercise in a previous section of this course, and make it derive from the OvenCA rather than OvenC class. As shown above, call this new Class OvenSA. Make sure that OvenSA s print( ) Copyright Russell Tront, Page 11-9 Copyright Russell Tront, Page 11-10

6 11.3 Interfaces Interfaces are a great new concept that is elegantly used in several parts of Java. An interface is a specification of the function signatures that one or several classes must implement. Writing an interface is like writing a standard for the function signatures that a class or group of classes, whether related by inheritance or not, must provide. As such, it allows a kind of polymorphism not possible in C++. Interfaces, in essence, specify the formats of the function call messages that you can send to an object that complies with that interface s standard. Recall that, in an earlier part of the course, it was suggested that the Smalltalk programming language uses the terminology of sending a message containing a function name and parameter values to an object instance. The method of that object that matches the message will as a result be executed. Well, a message to invoke a particular function must have a particular format containing a function name and a list of parameter types unique to that function. Interestingly, instances of several different classes, even if not related by inheritance, could potentially have a similarly named function invoked by such a message. This is because the message contains exactly the information needed (function name and compliant sequence of argument parameters) for invocation of the function. Specifying a function in an interface is essentially similar to specifying an abstract member function (i.e. no function body). But unlike an abstract class, no attributes are allows in an interface, and NONE of the functions can have a body. Copyright Russell Tront, Page So, an interface is just a list of function signatures. (Later we will see that an interface can also contain static final constants). Interfaces are used by the Java GUI libraries for specifying the standard that an object you write must comply with in order to be called back, say, regarding mouse Button clicks. This allows Sun to write Button class functions which accept registrations of objects for call backs, even though these library functions do not know the name of the class that you are writing to be the target of the call back. Sun documents the standard for objects that need to receive Button callbacks in an interface called ActionListener. Such interfaces are widely used in the Java Abstract Windowing Toolkit (AWT), Swing GUI components, and any other classes needing function call standards. In addition, when using so-called remote objects on another machine, you cannot directly access public attributes of that remote object. You can only call general functions, and get and set functions that affect the remote attributes, using Remote Method Invocation (RMI). As such, all a local client program needs to know about a remote client is the function names and parameters that it can accept. Of course, this is exactly what interfaces are good at specifying. Other important languages and technologies have the concept of interfaces. Microsoft s ActiveX and DCOM technology heavily uses the concept of interfaces written in a special language called MIDL (Microsoft Interface Definition Language). Most interface names from Microsoft begin with an upper case I, which is not a bad way to Copyright Russell Tront, Page 11-12

7 distinguish them from class names. In addition, the very important CORBA remote object technology heavily relies on interfaces written in plain IDL. One of the reasons for interfaces is to allow the compiler to check your calling code uses the correct function name and parameter list. As such, an interface provides an advertisement that allows the calling code to be checked against during compilation. Of course, classes that purport to comply with this standard must declare so, and when they are compiled, the compiler ensures that the programmer of the implementing class actually does provide complete functions complying with the advertisement. As such, then, interfaces form a agreement between implementing classes and using classes. This agreement is only loosely tied to each class. This provides another aspect of the safety, yet flexibility, of Java s strong type checking. Copyright Russell Tront, Page Declaring An Interface Here is an example of the declaration of an interface: public interface DownCounter { void setcount(int newvalue); int decrement(); This interface abstractly defines how you would call to preset a counter, and then decrement it (which returns the resultant decremented value). Or, it could be used to set and decrement the altitude of an airplane in a video game. Java programmers use interfaces as a very simple way of specifying the functions that a class must implement without defining the server class. As such, it forms a kind of function services contract, like a legal contract written between two generic kinds of people. An interface is thus somewhat like a very abstract class, except that a class that purports to implements an interface does not need to inherit from it. Here are a few other differences between an abstract class, and an interface:. An interface cannot have member attributes, except public static constants. An interface therefore generally only advertises function signatures for use by other programmers. These programmers might implement classes that comply with the interface, or they might Copyright Russell Tront, Page 11-14

8 write application programs that use references that point to objects of unspecified classes that implement that interface. The method bodies of EVERY method must be absent. There should not even be empty braces{ for the body. All members of an interface are by default public, so you do not have to label them public. All constants are by default public static final, and do not need to be so labeled. Only the interface itself needs to be labeled public, private, or not at all (package access). Sun Microsystems states that interfaces are useful for the following: Specifying member function similarities between unrelated classes without artificially forcing a inheritance relationship on or between them. Declaring methods that one or more classes are expected to implement. Revealing an object's programming interface without revealing its class name. Interfaces are used extensively in some parts of Java, in particular in Java RMI and in the Java GUI system (called Abstract Windowing Toolkit and Swing). Interfaces allow another type of polymorphism, a type that is not related in any way to inheritance. This is particularly useful when, say, a Button icon when clicked in a Java applet doesn t know whether it is to call an actionperformed( ) member function on a Frame class Copyright Russell Tront, Page instance, a Panel class instance, an Oven class instance, or whatever. It doesn t really care. It has simply been told to call the actionperformed( ) function on an instance reference that is known to refer to some instance that implements the ActionListener interface. Copyright Russell Tront, Page 11-16

9 Using an Interface and Interface Polymorphism Students are often not familiar with how to use an interface because textbooks usually just show how to write a class that implements an interface. So here is an example of how an application programmer might use an interface type: you know, say, that the potential referred instances are at least related by inheritance. Instead, they are related by the fact they promise to implement a particular interface. (Note: You can often use the instanceof operator and/or Java Reflection with an interface reference to find out what kind of instance d actually refers to.) DownCounter d = new Airplane( ); The variable d is a reference to some kind of object that implements the two functions in the DownCounter interface above. This variable could, as shown above, refer to an instance of an Airplane class that has an altitude that can be set and decremented. Or later in a program it could refer to a Submarine class instance whose depth can be changed. Or, equally validly refer to an instance of a concrete DownCounterImpl class that simply contains an integer that can be decremented. The d variable can be thought of polymorphically, even though interestingly the various kinds of things it might refer to at different moments during execution are NOT related by inheritance! The programmer is nonetheless assured by Java that, no matter where the reference was obtained (do you trust your sources?) and irrespective of the underlying instance type it refers to, he/she can still legally execute a statement like: d.decrement(); So an interface reference is like an object reference, but the exact class of the referred to instance is not clear. Nor do Copyright Russell Tront, Page Copyright Russell Tront, Page 11-18

10 Implementing an Interface The DownCounter interface name is not the name of a class, so you cannot instantiate a DownCounter itself. As you saw above, we only defined a reference to something that implemented the DownCounter interface. For an instance to be assignable to an interface variable, the instance s class must meet certain criteria. The instance s class must implement the functions of the interface. Here is how it is done. public class DownCounterImpl implements DownCounter{ define any necessary member attributes needed to implement the advertised functions. actually provide function bodies that implement the advertised functions. Note the implementing class can provide additional functions not advertised in the interface if the programmer wants them for other purposes. Also note that several different classes could be written to implement the DownCounter interfaces. For example, in addition to the DownCounterImpl class, an Airplane class, a Submarine class, and an OvenTemperature class. //here is the where the counter is stored. private int thecount; public void setcount(int newvalue){ thecount = newvalue; public int decrement(){ thecount--; return thecount; The main issues in writing a class whose instances can be assigned to an interface reference variable are, to: declare right after the class name implements DownCounter. Copyright Russell Tront, Page Copyright Russell Tront, Page 11-20

11 11.4 Exercise B Take the abstract class OvenCA from the previous exercise, and convert it to an interface called OvenI. Then copy the class OvenSA over to a new class OvenSI. Change OvenSI so that it can implement OvenI. Hints and Questions: Can the interface OvenI still have constructors? Can the class OvenSI still be a subclass? Can the class OvenSI chain back to the superclass s constructors, non-overridden functions, and overridden functions? Here is a UML diagram of the architecture for this exercise. Note that UML identifies an interface with <<interface>> before the class name. And indicates implementing an interface with a dotted, inheritance-looking line. Copyright Russell Tront, Page <<interface>> OvenCA setoven( ) print( ) OvenSI temperature pressure percentoxygen percenthumidity setoven( ) print( ) static main( ) Notice that with OvenI being an interface, OvenSI has to provide all attributes and all method bodies. For brevity, I have dropped the static PrintOven( ) method. The above exercise will have you practice the elements of defining and implementing interfaces, but not the polymorphism use of interfaces. To do that, you would have to define two different classes that both implemented the same interface, perhaps both OvenSI and Fridge. A Fridge object would also have temperature, pressure, percenthumidity, et cetera, that could be set and printed. You might want to call the interface something more general than OvenI; perhaps MonitorableContainerI or IControllableAirspace. Then a polymorphic program could Copyright Russell Tront, Page 11-22

12 define an interface reference variable and could assign different kinds of instances to it: IcontrollableAirspace myairspaceobject myairspaceobject = new OvenSI( ); myairspaceobject = new Fridge( ); 11.5 Multiple Interfaces Most people will tell you that Java does not have multiple inheritance. That is not true. It is true that you cannot write a class that inherits from two parent classes. However, you can write an interface that inherits from two parent interfaces. Nevertheless, remember that an interface has no function implementation bodies to inherit and re-use. Therefore, an interface that inherits from two other interfaces just ends up with the signatures from those two, plus any it adds on its own. It is written this way: public interface Composite extends I1, I2 { void f( ); So interface Composite has all the function signatures and constants of interface I1, and of interface I2, and also function signature void f( ); In addition, a Java class can declare that it implements more than one interface, also using the comma notation: class C implements I1, I2 {/*body here*/ Finally, what is commonly done to simulate the multiple class inheritance feature that is in C++, but missing from Java, is to declare a subclass that inherits from one class and implement an interface. In this case, you use both the extends and implements keywords. e.g. class Mult extends Base implements Inter{ Copyright Russell Tront, Page Copyright Russell Tront, Page 11-24

13 11.6 Interface Constants and Other Weird Things You can put a few more kinds of things in an interface. Public static final constants are the most common. e.g. public interface Counter { int UPMODE = 1; int DOWNMODE = -1; void setmode(int mode); int count(); You don t have to bother labeling them public static final. You can also put nested class and nested interface definitions within an interface. Nested classes will be discussed in a different section of this course. Copyright Russell Tront, Page 11-25

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System?

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System? Page 1 of 21 Page 2 of 21 and identity. Objects are members of a class, and the attributes and behavior of an object are defined by the class definition. The Essence of Object Oriented Programming with

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract methods Abstract Classes and Interfaces You can declare an object without defining it: Person p; Similarly, you can declare a method without defining it: public abstract void draw(int size); Notice

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

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

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 1 Problem Ralph owns the Trinidad Fruit Stand that sells its fruit on the street, and he wants to use a computer

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

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

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

Educational Fusion. Implementing a Production Quality User Interface With JFC

Educational Fusion. Implementing a Production Quality User Interface With JFC Educational Fusion Implementing a Production Quality User Interface With JFC Kevin Kennedy Prof. Seth Teller 6.199 May 1999 Abstract Educational Fusion is a online algorithmic teaching program implemented

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

16 Multiple Inheritance and Extending ADTs

16 Multiple Inheritance and Extending ADTs Object-Oriented Design Lecture 16 CS 3500 Fall 2009 (Pucella) Tuesday, Nov 10, 2009 16 Multiple Inheritance and Extending ADTs We looked last time at inheritance and delegation as two ways to reuse implementation

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information

3. Simple Types, Variables, and Constants

3. Simple Types, Variables, and Constants 3. Simple Types, Variables, and Constants This section of the lectures will look at simple containers in which you can storing single values in the programming language C++. You might find it interesting

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: has a CSE143 Sp Student. CSE 143 Java Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor CSE 143 Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog Dog

More information

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Define and discuss abstract classes Define and discuss abstract methods Introduce polymorphism Much of the information

More information

Java Programming Lecture 7

Java Programming Lecture 7 Java Programming Lecture 7 Alice E. Fischer Feb 16, 2015 Java Programming - L7... 1/16 Class Derivation Interfaces Examples Java Programming - L7... 2/16 Purpose of Derivation Class derivation is used

More information

We are on the GUI fast track path

We are on the GUI fast track path We are on the GUI fast track path Chapter 13: Exception Handling Skip for now Chapter 14: Abstract Classes and Interfaces Sections 1 9: ActionListener interface Chapter 15: Graphics Skip for now Chapter

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

UML & OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 3 08/30/2011

UML & OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 3 08/30/2011 UML & OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 3 08/30/2011 1 Goals of the Lecture Review the material in Chapter 2 of the Textbook Cover key parts of the UML notation

More information

16. Linked Structures and Miscellaneous

16. Linked Structures and Miscellaneous 16. Linked Structures and Miscellaneous The main purpose of this section is to look at the cool topic of linked data structures. This is where we use one object to point to the next object in a structure

More information

Object-oriented features

Object-oriented features Chapter 1 Object-oriented features The compiler s job for a procedural language like C is relatively straightforward, because C and most other compiled procedural languages have been designed to approximate

More information

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: has a CSC Employee. Supervisor CSC 143 Object & Class Relationships Inheritance Reading: Ch. 10, 11 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

Motivations. Chapter 13 Abstract Classes and Interfaces

Motivations. Chapter 13 Abstract Classes and Interfaces Chapter 13 Abstract Classes and Interfaces CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations You have learned how to write simple

More information

Logistics. Final Exam on Friday at 3pm in CHEM 102

Logistics. Final Exam on Friday at 3pm in CHEM 102 Java Review Logistics Final Exam on Friday at 3pm in CHEM 102 What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create

More information

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

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 13 Abstract Classes and Interfaces Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations You have learned how to write simple programs

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #23: OO Design, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia HW#5 due Tuesday And if you re cheating on (or letting others see your) HW#5

More information

CSE 70 Final Exam Fall 2009

CSE 70 Final Exam Fall 2009 Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007 Object Fundamentals Part Three Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007 1 Lecture Goals Continue our tour of the basic concepts, terminology, and notations

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August Polymorphism, Dynamic Binding and Interface 2 4 pm Thursday 7/31/2008 @JD2211 1 Announcement Next week is off The class will continue on Tuesday, 12 th August 2 Agenda Review Inheritance Abstract Array

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

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

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 26. Interfaces Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Definition The Comparable Interface Interfaces vs. Abstract Classes Creating Custom Interfaces References Definition Definition Single

More information

CPS122 Lecture: Detailed Design and Implementation

CPS122 Lecture: Detailed Design and Implementation CPS122 Lecture: Detailed Design and Implementation Objectives: Last revised March 3, 2017 1. To introduce the use of a complete UML class box to document the name, attributes, and methods of a class 2.

More information

Object Fundamentals. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 2 08/30/2007

Object Fundamentals. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 2 08/30/2007 Object Fundamentals Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 2 08/30/2007 1 Lecture Goals Introduce basic concepts, terminology, and notations for object-oriented analysis,

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

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

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 25. Interfaces Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Definition The Comparable Interface Interfaces vs. Abstract Classes Creating Custom Interfaces References Definition Definition Sometimes

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

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

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class Motivations Chapter 13 Abstract Classes and Interfaces You have learned how to write simple programs to create and display GUI components. Can you write the code to respond to user actions, such as clicking

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

Appendix A - Glossary(of OO software term s)

Appendix A - Glossary(of OO software term s) Appendix A - Glossary(of OO software term s) Abstract Class A class that does not supply an implementation for its entire interface, and so consequently, cannot be instantiated. ActiveX Microsoft s component

More information

MODULE 3q - An Extended Java Object

MODULE 3q - An Extended Java Object MODULE 3q - An Extended Java Object THE BOX PROGRAM RENAMED Copy the file Box.java to Block.java and then make all the amendments indicated by comments in the program below. The name of the public class

More information

Type Checking and Type Equality

Type Checking and Type Equality Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 31 Static Members Welcome to Module 16 of Programming in C++.

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

Inheritance and Polymorphism in Java

Inheritance and Polymorphism in Java Inheritance and Polymorphism in Java Introduction In this article from my free Java 8 course, I will be discussing inheritance in Java. Similar to interfaces, inheritance allows a programmer to handle

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics Inf1-OP Inf1-OP Exam Review Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 20, 2017 Overview Overview of examinable material: Lectures Week 1

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Java How to Program, 8/e

Java How to Program, 8/e Java How to Program, 8/e Polymorphism Enables you to program in the general rather than program in the specific. Polymorphism enables you to write programs that process objects that share the same superclass

More information

More on Inheritance. Interfaces & Abstract Classes

More on Inheritance. Interfaces & Abstract Classes More on Inheritance Interfaces & Abstract Classes Java interfaces A Java interface is used to specify minimal functionality that a client requires of a server. A Java interface contains: method specifications

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using Java Provided Classes In this lesson we'll focus on using the Graphics class and its capabilities. This will serve two purposes: first

More information

CS Lecture #6. Administrative... Assignment #2 Graded NN Turned In, Average Grade: XX Assignment #3 due on Thursday

CS Lecture #6. Administrative... Assignment #2 Graded NN Turned In, Average Grade: XX Assignment #3 due on Thursday CS 213 -- Lecture #6 Late Night Guide to C++ Chapter 5 INHERITANCE Administrative... Assignment #2 Graded NN Turned In, Average Grade: XX Assignment #3 due on Thursday The Conceptual Side of Classes Earlier

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Object Fundamentals, Part One. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 2 08/27/2009

Object Fundamentals, Part One. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 2 08/27/2009 Object Fundamentals, Part One Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 2 08/27/2009 1 Lecture Goals Introduce basic concepts, terminology, and notations for object-oriented

More information

1 OBJECT-ORIENTED PROGRAMMING 1

1 OBJECT-ORIENTED PROGRAMMING 1 PREFACE xvii 1 OBJECT-ORIENTED PROGRAMMING 1 1.1 Object-Oriented and Procedural Programming 2 Top-Down Design and Procedural Programming, 3 Problems with Top-Down Design, 3 Classes and Objects, 4 Fields

More information

CS112 Lecture: Inheritance and Polymorphism

CS112 Lecture: Inheritance and Polymorphism CS112 Lecture: Inheritance and Polymorphism Last revised 4/10/08 Objectives: 1. To review the basic concept of inheritance 2. To introduce Polymorphism. 3. To introduce the notions of abstract methods,

More information

CS211 Lecture: Relationships Between Classes: Dependency, Inheritance, and Realization

CS211 Lecture: Relationships Between Classes: Dependency, Inheritance, and Realization CS211 Lecture: Relationships Between Classes: Dependency, Inheritance, and Realization Objectives: last revised July 21, 2003 1. To introduce the dependency relationship between classes 2. To review the

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

CS Exam 1 Review Suggestions

CS Exam 1 Review Suggestions CS 235 - Fall 2015 - Exam 1 Review Suggestions p. 1 last modified: 2015-09-30 CS 235 - Exam 1 Review Suggestions You are responsible for material covered in class sessions, lab exercises, and homeworks;

More information

Lecture 11. Demonstration #1. More Inheritance, More Constructors. Absolute C++ Chapter 15. Virtual Functions. Overriding

Lecture 11. Demonstration #1. More Inheritance, More Constructors. Absolute C++ Chapter 15. Virtual Functions. Overriding Lecture 11 More Inheritance, More Constructors Absolute C++ Chapter 15 Overriding Let s recall the code we were working on from last lecture. We had a base class named Person and two derived classes named

More information

UML & OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 3 09/04/2012

UML & OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 3 09/04/2012 UML & OO Fundamentals CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 3 09/04/2012 1 Goals of the Lecture Review the material in Chapter 2 of the Textbook Cover key parts of the UML notation

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

Inheritance. Chapter 7. Chapter 7 1

Inheritance. Chapter 7. Chapter 7 1 Inheritance Chapter 7 Chapter 7 1 Introduction to Inheritance Inheritance allows us to define a general class and then define more specialized classes simply by adding new details to the more general class

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

(Refer Slide Time: 02.06)

(Refer Slide Time: 02.06) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 27 Depth First Search (DFS) Today we are going to be talking

More information

Chapter 13 Abstract Classes and Interfaces

Chapter 13 Abstract Classes and Interfaces Chapter 13 Abstract Classes and Interfaces rights reserved. 1 Motivations You have learned how to write simple programs to create and display GUI components. Can you write the code to respond to user actions,

More information

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

Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 5 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 2 is in Assignment 3 is out a quick look back inheritance and polymorphism interfaces the Comparable

More information

C++ Inheritance and Encapsulation

C++ Inheritance and Encapsulation C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

CSC207 Week 4. Larry Zhang

CSC207 Week 4. Larry Zhang CSC207 Week 4 Larry Zhang 1 Logistics A1 Part 1, read Arnold s emails. Follow the submission schedule. Read the Q&A session in the handout. Ask questions on the discussion board. Submit on time! Don t

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

5.6.1 The Special Variable this

5.6.1 The Special Variable this ALTHOUGH THE BASIC IDEAS of object-oriented programming are reasonably simple and clear, they are subtle, and they take time to get used to And unfortunately, beyond the basic ideas there are a lot of

More information

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:

More information

A short introduction to Web Services

A short introduction to Web Services 1 di 5 17/05/2006 15.40 A short introduction to Web Services Prev Chapter Key Concepts Next A short introduction to Web Services Since Web Services are the basis for Grid Services, understanding the Web

More information

Programming Exercise 14: Inheritance and Polymorphism

Programming Exercise 14: Inheritance and Polymorphism Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

After a lecture on cosmology and the structure of the solar system, William James was accosted by a little old lady.

After a lecture on cosmology and the structure of the solar system, William James was accosted by a little old lady. Introduction After a lecture on cosmology and the structure of the solar system, William James was accosted by a little old lady. Your theory that the sun is the centre of the solar system, and the earth

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information