To operate on values from different classes in Java, you can use methods to access and modify the values.
Here is an example of how you can operate on values from different classes in Java:
public class Main { public static void main(String[] args) { MyClass myClass = new MyClass(); int result = myClass.add(2, 3); System.out.println("Result: " + result); } } class MyClass { private int value1; private int value2; public MyClass() { value1 = 0; value2 = 0; } public void setValue1(int value) { value1 = value; } public void setValue2(int value) { value2 = value; } public int getValue1() { return value1; } public int getValue2() { return value2; } public int add(int value1, int value2) { return value1 + value2; } }
In this example, the Main
class has a main
method that creates an instance of the MyClass
class and calls the add
method to add two values. The MyClass
class has two private fields, value1
and value2
, and several methods to access and modify these fields. The setValue1
and setValue2
methods are used to set the values of the fields, and the getValue1
and getValue2
methods are used to get the values of the fields. The add
method is used to add the values of the fields and return the result.
Keep in mind that this is just one way to operate on values from different classes in Java. You can use different methods and techniques to achieve the same result, such as using constructors to initialize the fields, or using static fields and methods to access and modify the values.