How to create the multiple class in Java? Please elaborate it by using the example.
Java Code:
Output Snapshot:
Text Code:
// Class1 Declaration
class Class1 {
// Class1 Member Variable
int class1_variable;
// Class1 Member Functions
public void add(int x, int y) {
class1_variable = x + y;
System.out.println("In Class 1 : Addition result:
"+class1_variable);
}
public void sub(int x, int y) {
class1_variable = x - y;
System.out.println("In Class 1 : Subtraction result:
"+class1_variable);
}
}
// Class2 Declaration
class Class2 {
// Class2 Member Variable
int class2_variable;
// Class2 Member Functions
public void add(int x, int y) {
class2_variable = x + y;
System.out.println("In Class 2 : Addition result:
"+class2_variable);
}
public void sub(int x, int y) {
class2_variable = x - y;
System.out.println("In Class 2 : Subtraction result:
"+class2_variable);
}
}
// Main Class - Entry point of code
public class Main
{
public static void main(String[] args) {
// Creating object1 object of Class1
Class1 object1 = new
Class1();
// Calling add() and sub() member
function using object1
object1.add(20,10);
object1.sub(20,10);
// Creating object2 object of
Class1
Class2 object2 = new
Class2();
// Calling add() and sub() member
function using object1
object2.add(30,20);
object2.sub(30,20);
}
}
Explanation:
Get Answers For Free
Most questions answered within 1 hours.