228k views
5 votes
Write a full class definition for a class named Counter, and containing the following members:________

A data member counter of type int.
A constructor that takes one int argument and assigns its value to counter
A function called increment that accepts no parameters and returns no value. increment adds one to the counter data member.
A function called decrement that accepts no parameters and returns no value. decrement subtracts one from the counter data member.
A function called getValue that accepts no parameters. It returns the value of the instance variable counter.

1 Answer

2 votes

Answer:

The class definition for above problem in java is as follows:-

Step-by-step explanation:

class Counter // class counter

{

int counter; // variable counter

Counter(int v) // construtor

{

counter=v;

}

void increment() //increment function

{

counter=counter+1;

}

void decrement() //decrement function

{

counter=counter-1;

}

int getValue() //getvalue function

{

return counter;

}

}

Code Explanation:

  • The above class definition is in java language.
  • In this code, the name of the class is a Counter and it holds the three functions (increment, decrement and getvalue) and one constructor which is mentioned in the question.
  • To call the above class and their function firstly the user needs to create an object of the counter class in the main function by passing the one integer value on it.
  • The object declaration statement calls the constructor.
  • And then any function can be called by the object of the class with the help of the dot operator.