117k views
5 votes
Write a full class definition for a class named Acc2, and containing the following members: A data member named sum of type integer. A constructor that accepts no parameters. The constructor initializes the data member sum to 0. A member function named getSum that accepts no parameters and returns an integer. getSum returns the value of sum.

2 Answers

4 votes

Answer:

The simple code is given below in C++ with appropriate comments

Step-by-step explanation:

#include <iostream>

using namespace std;

// Write a full class definition for a class named Acc2

class Acc2 {

private:

// A data member named sum of type integer.

int sum;

public:

// A constructor that accepts no parameters. The constructor initializes the data member sum to 0.

Acc2() {

sum = 0;

}

// A member function named getSum that accepts no parameters and returns an integer.

// getSum returns the value of sum.

int getSum() {

return sum;

}

};

int main() {

return 0;

}

User Jabbermonkey
by
5.8k points
6 votes

Answer:

The JAVA code to represent the given class is shown below.

class Acc2 {

// integer variable declared

int sum;

Acc2()

{

// variable initialized inside the constructor

sum = 0;

}

// no parameters, only value is returned

int getSum()

{

// value of variable is returned

return sum;

}

}

Explanation:

The above class definition shows an integer variable sum which is initialized to 0 inside the constructor. The only method inside the class returns the value of variable sum. This method does not accepts any parameter.

The JAVA program to implement the above class is shown below.

class Acc2 {

int sum;

Acc2()

{

sum = 0;

}

int getSum()

{

return sum;

}

}

public class MyClass{

public static void main(String args[]) {

// object of Acc2 class is created

Acc2 ob = new Acc2();

// sum variable is displayed by calling the method and using the object

System.out.println("The value of sum is " + ob.getSum() );

}

}

OUTPUT

The value of sum is 0

As seen, another class is created which holds the main method. The object of other class is created inside the main. This is done using new operator.

Acc2 ob = new Acc2();

The method to print the value of variable sum is called through the use of this object.

ob.getSum()

It is important to note that the class which holds the main method is declared as public. This is because the main method is used to call the methods of other classes and hence, main method should be accessible outside its class.

The other class is not declared as public. This class should only be accessible to main method so that the object can be created inside the main().

While exporting the program, .class file is created only for the classes which are declared as public. In this case, the .class file will only be created for the class which holds the main method.

User Btzs
by
5.5k points