Question: Java: package countertest; class Counter { private int intCount; // integer instance variable public Counter() { intCount = 0; } public Counter( int init )
Java:
package countertest; class Counter { private int intCount; // integer instance variable public Counter() { intCount = 0; } public Counter( int init ) { intCount = init; // Constructor, initialize to 0 } public int getInteger() // Retrieve current count value { return this.intCount; } public void add( int value ) // Add to count value { this.intCount += value; } public void subtract( int value ) // Subtract from count value { if ( value <= this.intCount ) // Make sure it doesn't go negative { this.intCount -= value; } } } Task #1 The Counter Class For this lab we are going to enhance the Counter class. Please download the template, counter.java, to begin with. This class contains instance variables and methods used for the Counter class, which is used to increment and decrement an integer instance variable. This template also contains a Test Class to test the class. Task #2 Enhance the Counter class to include a double variable, called doubleCount; Task #3 Modify the default Constructor to initialize the new variable to 0.0; Task #4 Create a named constructor to initialize only the double variable; Task #5 Create a method, called getDouble(), to retrieve the double instance variable. Task #6 Add an overloaded method, add(), which passes in a double variable and adds it to the new double instance variable. This method is a duplication of the existing add() method but the calling parameter will allow the compiler determine which proper method should be called. Task #7 Add an overload method, subtract(), which passes in a double variable and subtracts it from the new double instance variable if it is less than or equal to the double instance variable. This method is a duplication of the existing add() method but the calling parameter will allow the compiler determine which proper method should be called. The following test class can be used to replace the one in the template file to test your new Class.
public class CounterTest { public static void main(String[] args) { Counter count1 = new Counter( 0 ); Counter count2 = new Counter( 0.0 ); System.out.println( "Value of Counters are " + count1.getInteger() + " and " + count2.getDouble()); count1.add( 15 ); count2.add( 15.0 ); System.out.println( "Value of Counters are " + count1.getInteger() + " and " + count2.getDouble()); count1.subtract( 3 ); count2.subtract( 3.0 ); System.out.println( "Value of Counters are " + count1.getInteger() + " and " + count2.getDouble()); } } which will result in the following output: Value of Counters are 0 and 0.0 Value of Counters are 15 and 15.0 Value of Counters are 12 and 12.0
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
