Session 5 More on Java Strings and Files & Intro. to Inheritance.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Lecture 15: I/O and Parsing
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
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.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Session 4 Command-Line Arguments, Strings, and Files.
Io package as Java’s basic I/O system continue’d.
Java I/O Input: information brought to program from an external source
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
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.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Two Ways to Store Data in a File Text format Binary format.
Session 05 Java Strings and Files. Exercise Complete the “quick-and-dirty” class CharacterCounter containing only a main() method that displays the number.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File IO Basics By Dan Fleck Coming up: Data Streams.
Chapter 15 Text Processing and File Input/Output Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
Session 6 Comments on Lab 3 & Implications of Inheritance.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
OO Design and Programming II I/O: Reading and Writing
Streams & File Input/Output (I/O)
University of Central Florida COP 3330 Object Oriented Programming
Objects, Classes, Program Constructs
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
Streams and File I/O Chapter 14.
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
File Input and Output.
Presentation transcript:

Session 5 More on Java Strings and Files & Intro. to Inheritance

Java File I/O Allows us to write and read “permanent” information to and from disk How would file I/O help improve the capabilities of the MemoPadApp?

Java File I/O Example: Echo.java echoes all the words in one file to an output file, one per line. $ java Echo hamlet.txt hamlet.out $ less hamlet.out 1604 the tragedy of hamlet prince of denmark by william shakespeare...

Study Echo.java’s File I/O have constructors that allow convenient and flexible processing send input message: readLine() send output messages: print() and println() use a stereotypical loop to process a file of lines use of the stereotypical StringTokenizer loop as inner loop

import java.io.*; import java.util.StringTokenizer; public class Echo { public static void main( String[] args ) throws IOException { String delimiters = ".?!()[]{}|?/&\\,;:-\'\"\t\n\r"; BufferedReader inputFile = new BufferedReader(new FileReader(args[0]) ); PrintWriter outputFile = new PrintWriter( new FileWriter( args[1] ) ); String buffer = null; while( true ) { buffer = inputFile.readLine(); if ( buffer == null ) break; buffer = buffer.toLowerCase(); StringTokenizer tokens = new StringTokenizer( buffer, delimiters ); while( tokens.hasMoreElements() ) { String word = tokens.nextToken(); outputFile.println( word ); } // end while } // end while(true)... } // end main } // end class Echo

wc - UNIX/Linux utility wc prints the number of lines, words, and characters in a file to standard output. For example: $ wc hamlet.txt hamlet.txt

Exercise Using Echo.java as your starting point, create a WordCount.java program that does the same thing as wc, i.e., prints the number of lines, words, and characters in a file to standard output. For example: $ java WordCount hamlet.txt lines = 4792 words = chars =

import java.io.*; import java.util.StringTokenizer; public class WordCount { public static void main( String[] args ) throws IOException { String delimiters = ".?!()[]{}|?/&\\,;:-\'\"\t\n\r"; BufferedReader inputFile = new BufferedReader( new FileReader( args[0] ) ); String buffer = null; int chars = 0; int words = 0; int lines = 0; while( true ) { buffer = inputFile.readLine(); if ( buffer == null ) break; lines++; buffer = buffer.toLowerCase(); StringTokenizer tokens = new StringTokenizer( buffer, delimiters ); while( tokens.hasMoreElements() ) { String word = tokens.nextToken(); words++; chars += word.length(); } // end while } // end while( true )... System.out.println( "" + lines + " " + words + " " + chars ); } // end main } // end class WordCount

Why the difference in the number of words and number of characters? $ wc hamlet.txt hamlet.txt $ java WordCount hamlet.txt lines=4792 words=32889 chars=130156

Java File I/O Example: Echo.java echoes all the words in one file to an output file, one per line. $ java Echo hamlet.txt hamlet.out $ less hamlet.out 1604 the tragedy of hamlet prince of denmark by william shakespeare...

import java.io.*; import java.util.StringTokenizer; public class Echo { public static void main( String[] args ) throws IOException { String delimiters = ".?!()[]{}|?/&\\,;:-\'\"\t\n\r"; BufferedReader inputFile = new BufferedReader(new FileReader(args[0]) ); PrintWriter outputFile = new PrintWriter( new FileWriter( args[1] ) ); String buffer = null; while( true ) { buffer = inputFile.readLine(); if ( buffer == null ) break; buffer = buffer.toLowerCase(); StringTokenizer tokens = new StringTokenizer( buffer, delimiters ); while( tokens.hasMoreElements() ) { String word = tokens.nextToken(); outputFile.println( word ); } // end while } // end while(true)... } // end main } // end class Echo

Working with Standard Input and Output as Files Sometimes, we'd like to give the user an option of providing a file name or using standard I/O. We can call sort with its own file argument, or we can pipe the standard output of one program (cat hamlet.out) as the standard input to sort. How can we make our Java programs do the same thing?

Streams vs. Readers and Writers a stream is a device for transmitting or receiving a sequence of byte (8-bit) values –emphasis on reading/writing -- not on data itself –network and file systems are based on byte unit Readers and Writers use 16-bit Unicode –useful for I/O of textual values as opposed to binary data such as images, colors, etc. –for example, BufferedRead has readLine method

Working with Standard Input and Output as Files Standard input is an instance of the InputStream class and does not respond to readLine(), which is how we would like to grab lines of text as Strings. Standard output does respond to println() messages, but it is a PrintStream, which cannot be stored in a PrintWriter variable.

What can we do? We could write duplicate code for the four different cases. (file-file, file-stdout, stdin-file, stdin-stdout) Every case would look the same except for one or two lines. That doesn't seem to be the correct solution. Maybe we can find a way to have them talk to objects that talk to standard input and output...

A Solution Let's take advantage of an object-oriented idea: We ought to be able to substitute an object with a common interface, even if somewhat different behavior, in place of one another, and let the new object fulfill the responsibilities of the replaced one. While BufferedReaders and PrintWriters don't know how to talk to standard input and output, respectively, we can use a translator to serve as a go-between. Java give us the classes we need: InputStreamReader and OutputStreamWriter.

import java.io.*; import java.util.StringTokenizer; public class EchoStandard { public static void main( String[] args ) throws IOException { String delimiters = ".?!()[]{}|?/&\\,;:-\'\"\t\n\r"; BufferedReader inputFile = new BufferedReader( new InputStreamReader( System.in ) ); PrintWriter outputFile = new PrintWriter( new OutputStreamWriter( System.out ) ); String buffer = null; while( true ) { buffer = inputFile.readLine(); if ( buffer == null ) break; buffer = buffer.toLowerCase(); StringTokenizer tokens = new StringTokenizer(buffer,delimiters); while( tokens.hasMoreElements() ) { String word = tokens.nextToken(); outputFile.println( word ); } // end while } // end while( true )... } // end main } // end class EchoStandard

Echo BufferedReader inputFile = new BufferedReader( new FileReader( args[0]) ); PrintWriter outputFile = new PrintWriter( new FileWriter( args[1]) ); vs. EchoStandard BufferedReader inputFile = new BufferedReader( new InputStreamReader( System.in ) ); PrintWriter outputFile = new PrintWriter( new OutputStreamWriter( System.out ) );

Exercise Turn Echo.java into EchoV2.java, which behaves just like Echo, except that it takes two optional command-line arguments: the names of the input file and output file, respectively. If the user omits the second argument, the program writes to standard output. If the user omits both arguments, the program reads from standard output and writes to standard output. For example: $ java EchoV2 hamlet.txt hamlet.out $ less hamlet.out 1604 the tragedy of...

Exercise - More Examples $ java EchoV2 EchoV2.java... $ java EchoV2 hamlet.txt | less (interesting that the pipe “|” is not args[1]) 1604 the tragedy of... $ java EchoV2... $ cat hamlet.txt | java EchoV2 | less 1604 the tragedy of...

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.