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.