60.9k views
0 votes
Write the definition of a class Counter containing:

a. An instance variable named counter of type int An instance variable named limit of type int.
b. A constructor that takes two int arguments and assigns the first one to counter and the second one to limit
c. A method named increment. It does not take parameters or return a value; if the instance variable counter is less than limit, increment just adds one to the instance variable counter.
d. A method named decrement. It also does not take parameters or return a value; if counter is greater than zero, it just subtracts one from the counter.
e. A method named getValue that returns the value of the instance variable counter.

User Cyt
by
5.3k points

1 Answer

3 votes

Answer:

Answer is in java language.

Step-by-step explanation:

Java Code

a) Creating instance variable

public class Counter {

int counter;

int limit;

}

Code Explanation

create a public class and declare variables inside the class block. By doing this, it will create instance variable of that class.

b) Constructor

public Counter(int first, int second){

this.counter=first;

this.limit=second;

}

Code Explanation

Constructor are method having no return type and having exact name as Class name. Constructor are used to initialize the class instance before calling any other method.

c) Increment Method

public void increment(){

if(this.counter<this.limit){

counter++;

}

}

Code Explanation

void tells the compiler that there is nothing to return from current method. If block is checking the condition that if counter is less then the limit then increment the counter by 1.

d) Decrements Method

public void decrement(){

if(this.counter>0){

this.counter--;

}

}

Code Explanation

Decrement method will check if counter value is greater then 0 then decrement counter value by 1 in if block.

e) getValue method

public int getValue(){

return this.counter;

}

Code Explanation

getValue method will take no parameter as input and return the current counter value by using return statement.

Full Code Example

public class Counter {

int counter;

int limit;

public Counter(int first, int second){

this.counter=first;

this.limit=second;

}

public void increment(){

if(this.counter<this.limit){

counter++;

}

}

public void decrement(){

if(this.counter>0){

this.counter--;

}

}

public int getValue(){

return this.counter;

}

}

User Davidcondrey
by
4.5k points