Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.

Slides:



Advertisements
Similar presentations
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Advertisements

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
20-Jun-15 Methods. Complexity The programmer's biggest adversary is complexity The programmer's biggest adversary is complexity Primitive types and the.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
OOP Languages: Java vs C++
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
Programming Languages and Paradigms Object-Oriented Programming.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Introduction to Object-oriented programming and software development Lecture 1.
Session 5 More on Java Strings and Files & Intro. to Inheritance.
OOD Case Study (For parallel treatment, see Chapter 2 of the text)
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
CSC 142 Computer Science II Zhen Jiang West Chester University
Session 11 Border Layout, using Panels, Introduction to PinBallGame.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object Oriented Software Development
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
1 CS161 Introduction to Computer Science Topic #9.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming – Home and reload buttons for the webbrowser, Applets.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© 2007 Lawrenceville Press Slide 1 Chapter 8 Objects  A variable of a data type that is a class. Also called an instance of a class.  Stores data  Can.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
SEEM Java – Basic Introduction, Classes and Objects.
Session 6 Comments on Lab 3 & Implications of Inheritance.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Computer Science II 810:062 Section 01 Session 2 - Objects and Responsibilities.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
OOP Basics Classes & Methods (c) IDMS/SQL News
BY:- TOPS Technologies
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
External Scope CECS 277 Mimi Opkins.
User-Written Functions
Lecture 12 Inheritance.
Objects as a programming concept
Inheritance and Polymorphism
Review: Two Programming Paradigms
Week 6 Object-Oriented Programming (2): Polymorphism
CMSC 202 Exceptions.
CIS 110: Introduction to computer programming
Presentation transcript:

Session 7 Introduction to Inheritance

Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame - allows X button –Accumulator - internal representation and implementation of the accumulator

AdderApp contains the main() method that serves as the "Big Bang" for this part of the world public class AdderApp { public static void main( String[] args ) { AddingFrame f = new AddingFrame(); f.show(); } // end main } // end class AdderApp

AddingFrame Provides the graphical interaction between the user and the actual calculator methods AddingFrame extends CloseableFrame extends JFrame. AddingFrame depends on the Accumulator class do the mathematics for the program.

Accumulator Class Recall from CS I that a class contains three things. – Data / Instance Variables – Method(s) – Constructor(s)

Accumulator Class What Data / Instance Variables are needed?

Accumulator Class Data / Instance Variables needed: –currentSum – the current value “accumulated” by the accumulator. –currentNumber – the number that has been entered by the user. The value that will be added or subtracted. –displayValue – the value visible on the graphical calculator. (Needed because sometimes we display the number the user is entering (currentNumber) and sometimes it is the current accumulated value (currentSum), so we will maintain a new value which holds whatever is on display.)

Accumulator Class What methods would the accumulator class need (hint, there are five of them)?

Accumulator Class Needed methods: –plus – adds the last number entered to the currentSum. –minus – subtracts the last number entered from the currentSum. –clear – sets everything back to zero –addDigit – adjusts the currentNumber upon input of an additional integer –getDisplay – returns the current displayValue. (This is necessary because our graphical class will want to know what value to display any time some action occurs.)

Accumulator Class What would the constructor do?

AccumulatorV1 public class AccumulatorV1 { private int currentSum; private int currentNumber; private int displayNumber; public Accumulator() { currentSum=0; currentNumber=0; displayNumber=0; } public void clear() { currentSum=0; currentNumber=0; displayNumber=0; } public void addDigit( int digit ) { currentNumber=currentNumber*10+digit; displayNumber=currentNumber; } public void plus() { currentSum+=currentNumber; currentNumber=0; displayNumber=currentSum; } public void minus() { currentSum-=currentNumber; currentNumber=0; displayNumber=currentSum; } public int getDisplay() { return displayNumber; } } // end class AccumulatorV1

Refactoring Accumulator What is refactoring? –Changing a program in a way that does not change its functionality. Why do it? –To improve the structure of your code based on what you have learned since writing it. What common code can we refactor?

Refactoring Accumulator Using the clear() method in the constructor Refactoring the plus() and minus() methods to call a private helper method.

Refactoring Accumulator public void plus() { currentSum+=currentNumber; prepareForNextNumber(); } public void minus() { currentSum-=currentNumber; prepareForNextNumber(); } private void prepareForNextNumber() { currentNumber=0; displayNumber=currentSum; } public int getDisplay() { return displayNumber; } } // end class AccumulatorV2 public class AccumulatorV2 { private int currentSum; private int currentNumber; private int displayNumber; public Accumulator() { clear(); } public void clear() { currentSum=0; currentNumber=0; displayNumber=0; } public void addDigit( int digit ) { currentNumber=currentNumber*10+digit; displayNumber=currentNumber; }

Reinforcing the refactoring There is an old programmers adage that states "There are only two numbers: 1 and many" Once you start to repeat code, it is time to start to think about refactoring and adding in a helper method.

Alternative structure of the program The complete “calculator” consists of four classes. –AdderApp –AddingFrame –CloseableFrame –Accumulator

Alternative structure of the program We can think of the relationships between these four classes as being “narrow and deep” –AdderApp creates an instance of AddingFrame which creates an instance of Accumulator. –This is a good example of data hiding since AdderApp doesn’t know/care that there is an instance of the Accumulator class. public class AdderApp { public static void main( String[] args ) { AddingFrame f = new AddingFrame(); f.show(); } // end main } // end class AdderApp public class AddingFrame extends CloseableFrame { private Accumulator myAccumulator;... public AddingFrame( ) { // create frame and accumulator myAccumulator = new Accumulator();...

Alternative structure of the program But another way to structure this program would be to create a relationship which is “wide and shallow” –AdderApp creates an an instance of Accumulator which it passes to an instance of AddingFrame. public class AdderApp { public static void main( String[] args ) { Accumulator a = new Accumulator(); AddingFrame f = new AddingFrame(a); f.show(); } // end main } // end class AdderApp –This is a good example of composition. We emphasize that AddingFrame is composed of an Accumulator –This is a good example of writing code that is modular. Now that we know the composition relation, we can compose solutions using variations of Accumulator.

CountedAccumulator Extension Suppose we need a new kind of object, an Accumulator that counts how many operations it executes. Let’s call this class CountedAccumulator. It responds to all the same messages as a regular Accumulator and also responds to an operationsExecuted() message, by returning its count. What changes would you need to make to Accumulator?

Adding Behavior to a Class Any time that we need to add behavior to a class we have at least three options: –Add code to the class itself, keeping the original class. –Copy all the old code into a new class and add code to this new class. –Create a subclass that extends the original class' behavior.

Pros and Cons “Add code to the class itself, keeping the original class. “ –Pros: Quick. Convenient. Simple. –Cons: May change the behavior of the class. Thus, it isn’t always an option.

Pros and Cons “Add code to the class itself, keeping the original class. “ –Pros: Quick. Convenient. Simple. –Cons: May change the behavior of the class. Thus, it isn’t always an option.

Pros and Cons “Add code to the class itself, keeping the original class. “ –Pros: Quick. Convenient. Simple. –Cons: May change the behavior of the class. Thus, it isn’t always an option.

Pros and Cons “Copy all the old code into a new class and add code to this new class. “ –Pros: Quick. Convenient. Simple. –Cons: Duplicated code. Error trap! Error trap!

Pros and Cons “Copy all the old code into a new class and add code to this new class. “ –Pros: Quick. Convenient. Simple. –Cons: Duplicated code. Error trap! Error trap!

Pros and Cons “Copy all the old code into a new class and add code to this new class. “ –Pros: Quick. Convenient. Simple. –Cons: Duplicated code. Error trap! Error trap!

Pros and Cons “Create a subclass that extends the original class' behavior.“ –Pros: Doesn’t break existing code. Virtually eliminates duplicate code. Provides the most flexibility. –Cons: Slightly more time consuming.

Pros and Cons “Create a subclass that extends the original class' behavior.“ –Pros: Doesn’t break existing code. Virtually eliminates duplicate code. Provides the most flexibility. –Cons: Slightly more time consuming.

Pros and Cons “Create a subclass that extends the original class' behavior.“ –Pros: Doesn’t break existing code. Virtually eliminates duplicate code. Provides the most flexibility. –Cons: Slightly more time consuming.

Developing an Extended Class There are typically four steps in developing an extended class. –declare the class –declare the new data –create the constructors –adjust the methods

Developing an Extended Class declare the class public class CountedAccumulator extends Accumulator {

Developing an Extended Class declare the new data private int numberOfOperations;

Developing an Extended Class create the constructor public CountedAccumulator () { super(); numberOfOperations=0; }

Developing an Extended Class Leave inherited methods alone –clear() and prepareForNextNumber() are both inherited from Accumulator and there is no need to change them.

Developing an Extended Class Modify/Override inherited methods –plus() and minus() are inherited, but they don't do what we want them to. –We can make them do more without completely replacing the code however. public void plus() { super.plus(); numberOfOperations++; }

Developing an Extended Class Add completely new methods –We need an accessor method for numberOfOperations public void operationsExecuted() { return numberOfOperations; }

CountedAccumulator Solution public class CountedAccumulator extends Accumulator { private int numberOfOperations; public CountedAccumulator() { super();// calls the superclass’ constructor numberOfOperations=0; } public void plus() { super.plus(); numberOfOperations++; } public void minus() { super.minus(); numberOfOperations++; } public int getOperations() { return numberOfOperations; } } // end class CountedAccumulator

CountedAccumulator Solution Now, before we can really work with this we need to modify other files in our application. We need to set up the AddingFrame so that it works with a CountedAccumulator rather than a regular Accumulator. We do this in the AdderApp class for simplicity. Accumulator a = new CountedAccumulator(); AddingFrame f = new AddingFrame(a);

A solution Why do we do this in the AdderApp rather than leave it alone and modify the AddingFrame? –Because in the end this makes our AddingFrame slightly more versatile. –Think about it...AddingFrame works with an Accumulator (or CountedAccumulator). If one is provided, it uses it. If one is not provided, it creates it. –THAT, is more versatile than telling an AddingFrame to now always create a CountedAccumulator.

A solution Now we can run this... –Notice that we have basically returned to having a Accumulator. Why? –Notice that even though I have private data and methods in Accumulator, I didn't have to change this here. Why?

A solution that USES the counting functionality If we want to actually use the functionality of this new class, then something needs to call the new method in CountedAccumulator. Without discussing the details of exception handling, we could do this by writing: try { Thread.sleep(10000); } catch(Exception e) { } System.out.println("Performed“ +a.getOperations()+"operations");

Another Exercise Create a class named EvenOddAccumulator that subclasses Accumulator to implement this behavior. EvenOddAccumulators respond to all the same messages as regular Accumulators. But, in response to plus() and minus() messages, an EvenOddAccumulator both computes the new sum and writes a congratulatory message if the sum is even.

Toward a Solution Here is the critical new piece of the EvenOddAccumulator class: if ( currentSum % 2 == 0 ) { System.out.println( "Hurray! You made an even number." ); } The big question is, what else is a part of the class?

Toward a Solution Let’s look at one version of this…

A Problem Accessing Inherited Data $ javac EvenOddAccumulator.java EvenOddAccumulator.java:17: currentSum has private access in Accumulator if ( currentSum % 2 == 0 ) ^ EvenOddAccumulator.java:24: currentSum has private access in Accumulator if ( currentSum % 2 == 0 ) ^ 2 errors Oops! currentSum is declared as a private instance variable in class Accumulator. private means private: no code outside the Accumulator class can access that variable.

A Possible Solution for Accessing Inherited Data Change currentSum to be public or protected. public class Accumulator { protected int currentSum;... }

A Better Solution for Accessing Inherited Data (2) Add a protected “accessor” method to the Accumulator class. Use that method to access the currentSum instance variable in the subclass. public class Accumulator {... protected int currentSum() { return currentSum; } Then use currentSum() in EvenOddAccumulator.

Programming with Inheritance Inheritance is an object-oriented programming construct that enables us to add behavior to an existing system without modifying the existing classes.

Programming with Inheritance Our new EvenOddAccumulator class adds behavior to a program that uses Accumulators without modifying: the behavior of the existing Accumulator class or the existing AddingFrame class! That means... No chance of introducing an unnecessary, unexpected errors into the working Accumulator class. No need to modify programs that use instances of Accumulator but which don’t need instances of EvenOddAccumulator. The ability to use EvenOddAccumulators in programs that expect to use Accumulators.

Programming with Inheritance We could have achieved some of these results without using inheritance by creating a new class named EvenOddAccumulator that simply duplicated the behavior of existing Accumulator class. Using inheritance means that... No need to reimplement existing methods. No need to duplicate code. One of the most important features of object-oriented programming is that it encourages us to create new classes that reuse existing code as much as possible. Without inheritance, you have only one tool for doing that, composition. With inheritance, you have two tools.