Java OOP Example 1: Multi-Class Method Calls & Overloading

 // File 1: smo_1.java
public class smo_1 {
    public int my_add(int x, int y) {
        return x + y;
    }
}

 // File 2: smo_main.java
public class smo_main {
    public static void main(String[] args) {
        int x = 5;
        int y = 16;
        smo_1 obj1 = new smo_1();
        System.out.println(obj1.my_add(x, y));
    }
}

Output:

21

1. How smo_main.java and smo_1.java Work Together 🔝

Code Step File Location Runtime Action
int x = 5, y = 16; smo_main.java Declares two local int variables on main()'s stack frame.
smo_1 obj1 = new smo_1(); smo_main.java Allocates an instance of helper class smo_1 on the heap.
obj1.my_add(x, y) smo_main.java → smo_1.java Copies 5 and 16 into my_add parameters and returns 21.

2. Method Overloading: Multiple my_add() Signatures in smo_1 🔝

Java allows defining multiple methods with the exact same name (my_add) inside smo_1 as long as their parameter lists differ in argument count or parameter types (compile-time polymorphism):

public class smo_1 {
     // 1. Two int parameters
    public int my_add(int x, int y) { return x + y; }

     // 2. Three int parameters (Overloaded)
    public int my_add(int x, int y, int z) { return x + y + z; }

     // 3. Two double parameters (Overloaded)
    public double my_add(double x, double y) { return x + y; }

    public static void main(String[] args) {
        smo_1 obj1 = new smo_1();
        System.out.println("2 ints:    " + obj1.my_add(5, 16));
        System.out.println("3 ints:    " + obj1.my_add(5, 16, 9));
        System.out.println("2 doubles: " + obj1.my_add(5.5, 16.25));
    }
}

Terminal Output:

2 ints:    21
3 ints:    30
2 doubles: 21.75

3. Primitive Arguments Are Passed by Value 🔝

When smo_main passes int x = 5 to a method, Java passes a copy of the value 5. Reassigning the parameter x = 999 inside the called method never changes the variable x inside main():

class PassByValueDemo {
    void tryToModifyPrimitive(int x) {
        x = 999;  // Modifies only the local parameter copy!
    }
    public static void main(String[] args) {
        int x = 5;
        new PassByValueDemo().tryToModifyPrimitive(x);
        System.out.println("Caller x is still: " + x);
    }
}

Terminal Output:

Caller x is still: 5

4. Passing an Object Reference to a Method 🔝

When you pass an object (like Box myBox) to a method, the method receives a copy of the reference pointing to the same heap object. Modifying b.width inside the method updates myBox.width:

class Box {
    int width;
    Box(int width) { this.width = width; }
}

public class PassObjectDemo {
    static void scaleBox(Box b, int factor) {
        b.width *= factor;  // Modifies the heap object pointed to by b!
    }
    public static void main(String[] args) {
        Box myBox = new Box(10);
        scaleBox(myBox, 3);
        System.out.println("Scaled box width: " + myBox.width);
    }
}

Terminal Output:

Scaled box width: 30

5. Returning a Newly Created Object from a Method 🔝

A method is not limited to returning primitives like int; it can construct and return a brand-new class instance (such as an immutable Point2D):

class Point2D {
    int x, y;
    Point2D(int x, int y) { this.x = x; this.y = y; }
    Point2D translate(int dx, int dy) {
        return new Point2D(this.x + dx, this.y + dy);  // Returns a new object!
    }
}

public class ReturnObjectDemo {
    public static void main(String[] args) {
        Point2D p1 = new Point2D(5, 16);
        Point2D p2 = p1.translate(10, -6);
        System.out.println("Translated Point: (" + p2.x + ", " + p2.y + ")");
    }
}

Terminal Output:

Translated Point: (15, 10)

6. Comparison: Method Overloading vs Method Overriding 🔝

Aspect Method Overloading Method Overriding
Where Defined Within the same class (or subclass) In a subclass (extends parent)
Parameter List Must differ (count, types, or order) Must be identical to parent method
Return Type Can be anything (if parameters differ) Same type (or covariant subtype)
Binding Time Compile-time (static binding) Runtime (dynamic dispatch)

7. Practical Recipe: Stateful Service Class (TaxCalculator) 🔝

Why instantiate an object like new smo_1() instead of making every method static? Because an object can hold configuration state (such as a regional tax rate) initialized in its constructor:

class TaxCalculator {
    double rate;
    TaxCalculator(double rate) { this.rate = rate; }
    double computeTotal(double subtotal) {
        return subtotal + (subtotal * rate);
    }
}

public class InvoiceApp {
    public static void main(String[] args) {
        TaxCalculator gst = new TaxCalculator(0.18);
        System.out.println("Total with 18% GST: " + gst.computeTotal(1000.0));
    }
}

Terminal Output:

Total with 18% GST: 1180.0

8. Common Multi-File Compilation Pitfalls 🔝

Overloading Only by Return Type Is a Compile Error

Writing both int my_add(int x, int y) and double my_add(int x, int y) with identical parameter types fails to compile with method my_add(int,int) is already defined. Overloaded methods must have distinct parameter lists.

Package Visibility Trap Across Different Directories

In the legacy smo_1 class, int my_add(int x, int y) had default (package-private) visibility. If smo_main is placed in a different package, my_add must be declared public int my_add(int x, int y) so external packages can call it.

9. Complete Compilable Java Program 🔝

public class OopExample1FullDemo {
    static class MathHelper {
        int my_add(int a, int b) { return a + b; }
        int my_add(int a, int b, int c) { return a + b + c; }
    }
    public static void main(String[] args) {
        MathHelper h = new MathHelper();
        if (h.my_add(5, 16) == 21 && h.my_add(5, 16, 9) == 30) {
            System.out.println("All Java OOP Example 1 checks passed!");
        }
    }
}

Terminal Output:

All Java OOP Example 1 checks passed!

10. Frequently Asked Questions (FAQ) 🔝

How do I compile smo_main.java and smo_1.java from the command line?

Place both files in the same folder and run javac smo_main.java (the Java compiler automatically locates and compiles smo_1.java), then run java smo_main.

Does the parameter name inside smo_1.my_add(int x, int y) have to match x and y in smo_main?

No! Parameter names are local to each method. Defining int my_add(int a, int b) works identically when called with obj1.my_add(x, y).

What if I want to load smo_1 dynamically by its String class name at runtime?

Use Java Reflection with Class.forName("smo_1"), covered in the next tutorial (Java OOP Example 2: forName()).

Can a method accept a variable number of integers (varargs)?

Yes! Declaring int my_add(int... nums) allows callers to pass any number of arguments (obj1.my_add(1, 2, 3, 4)), which Java receives as an int[] array.

What happens if I pass two byte or short values to my_add(int x, int y)?

Java automatically widens smaller integer types (byte, short, char) to int without requiring an explicit cast.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer