Answer:
The java program for the given scenario is shown below.
import java.util.*;
import java.lang.*;
class YourClass
{
// two private integer variables are declared
private int num1, num2;
// constructor has the same name as the class itself
// constructor is similar to a method
// constructor has no return type
// constructor may or may not accept parameters
YourClass()
{
num1 = 1;
num2 = 2;
}
// first method
void add()
{
System.out.println("Sum of the numbers " + num1 + " and " + num2 + " is " + (num1+num2) );
}
// second method
void subtract()
{
System.out.println("Difference between numbers " + num1 + " and " + num2 + " is " + (num1-num2) );
}
}
public class Test
{
public static void main(String args[]) {
// object of the class, YourClass, is created
// since constructor takes no parameters, no parameters are passed to the object
YourClass ob = new YourClass();
// first method called
ob.add();
// second method called
ob.subtract();
}
}
OUTPUT
Sum of the numbers 1 and 2 is 3
Difference between numbers 1 and 2 is -1
Explanation:
1. The class, MyClass, contains two private fields, one constructor and two methods.
2. The fields are integer variables which are initialized in the constructor.
3. In the add() method, both integer variables are added and their sum displayed with System.println() method.
4. In the subtract() method, both integer variables are subtracted and their difference displayed with System.println() method.
5. In the other class, Test, inside the main() method, the object of the class, MyClass, is created.
6. Using the object, both the methods, add() and subtract(), are called inside main().
7. Java is a purely object-oriented language hence all the code is written inside classes.
8. Only the class which has main() method can be declared as public. Other classes are not declared public.