Skip to content
Qyubie Learn
Java tutorialLesson 13 of 18 · tap to see all lessons

Java tutorial · Beginner

Java Method Overloading and Object Interaction: Signatures, Composition, and Relationships

Overload Java methods correctly using signatures, pass objects to methods, have objects call each other, and build classes from other classes with composition.

  • Qyubie Learn Editorial Team
  • Published
  • 10 min read

Includes 3 quick checks you can do right here.

A real program is never one class working alone. An enrollment system has students, subjects, and sections, and they work together: a section has students, a student enrolls in a section. This lesson covers how objects talk to each other and how one class can be built from others. First, we finish a topic from lesson 8: method overloading, now on objects.

By the end of this lesson you will be able to:

  • explain a method's signature and the rules for overloading,
  • pass objects to methods and return objects from them,
  • have one object call methods on another, and
  • build a class from other classes (composition) and describe has-a and is-a relationships.

Method signatures and overloading

A method's signature is its name plus its parameter types, in order. Two methods in a class can share a name only if their signatures differ.

Pair of methodsOverload allowed?Why
add(int a, int b) and add(double a, double b)yesdifferent parameter types
add(int a, int b) and add(int a, int b, int c)yesdifferent number of parameters
show(String s, int n) and show(int n, String s)yesdifferent order of types
add(int a, int b) and add(int x, int y)noparameter names don't count
int total() and double total()nothe return type doesn't count

Overloaded methods in a class usually do "the same idea" for different inputs:

class Printer {
    void print(int n) {
        System.out.println("int: " + n);
    }

    void print(double d) {
        System.out.println("double: " + d);
    }

    void print(String s) {
        System.out.println("String: " + s);
    }

    void print(String s, int times) {
        for (int i = 0; i < times; i++) {
            System.out.print(s);
        }
        System.out.println();
    }
}

public class Main {
    public static void main(String[] args) {
        Printer p = new Printer();
        p.print(5);
        p.print(5.0);
        p.print("Hi");
        p.print("ab", 3);
        p.print('A');      // no print(char): char widens to int
    }
}

Output:

int: 5
double: 5.0
String: Hi
ababab
int: 65

Java picks the overload whose parameter types match the arguments best. When nothing matches exactly, it tries widening, so the char 'A' becomes the int 65 and print(int) runs.

Quick check

What does this print?
public class Main {
    static String f(long x) { return "long"; }
    static String f(double x) { return "double"; }
    public static void main(String[] args) {
        System.out.println(f(10));
    }
}

Passing objects to methods

A method can take an object as a parameter. What's passed is a copy of the reference, so the method works with the same object the caller has, and changes to its fields are visible afterwards:

class Account {
    String owner;
    double balance;

    Account(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    // One object interacting with another object of the same class
    void transferTo(Account other, double amount) {
        if (amount > balance) {
            System.out.println("Not enough funds");
            return;
        }
        this.balance -= amount;
        other.balance += amount;
    }
}

public class Main {
    public static void main(String[] args) {
        Account ana = new Account("Ana", 1000);
        Account ben = new Account("Ben", 200);
        ana.transferTo(ben, 300);
        System.out.println(ana.owner + ": " + ana.balance);
        System.out.println(ben.owner + ": " + ben.balance);
    }
}

Output:

Ana: 700.0
Ben: 500.0

Inside transferTo, this is Ana's account (the object the method was called on), and other is Ben's. One method call updated two objects.

A method can also return an object:

class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    Point moved(int dx, int dy) {
        return new Point(x + dx, y + dy);   // a new object; this one is unchanged
    }
}

public class Main {
    public static void main(String[] args) {
        Point a = new Point(1, 2);
        Point b = a.moved(3, 4);
        System.out.println(a.x + "," + a.y);
        System.out.println(b.x + "," + b.y);
    }
}

Output:

1,2
4,6

Composition: classes built from classes

Composition means a class has fields that are objects of other classes. It's how you model a has-a relationship: a Section has a list of Students, and a Student has an Address.

class Student {
    private String name;
    private double grade;

    Student(String name, double grade) {
        this.name = name;
        this.grade = grade;
    }

    String getName() { return name; }
    double getGrade() { return grade; }
}

class Section {
    private String code;
    private Student[] students = new Student[40];
    private int count = 0;

    Section(String code) {
        this.code = code;
    }

    void enroll(Student s) {
        if (count == students.length) {
            System.out.println("Section " + code + " is full");
            return;
        }
        students[count] = s;
        count++;
    }

    double average() {
        double sum = 0;
        for (int i = 0; i < count; i++) {
            sum += students[i].getGrade();   // Section asks each Student
        }
        return count == 0 ? 0 : sum / count;
    }

    void printRoster() {
        System.out.println("Section " + code + " (" + count + " students)");
        for (int i = 0; i < count; i++) {
            System.out.println("  " + (i + 1) + ". " + students[i].getName());
        }
        System.out.printf("  Average: %.2f%n", average());
    }
}

public class Main {
    public static void main(String[] args) {
        Section bscs1a = new Section("BSCS 1A");
        bscs1a.enroll(new Student("Ana", 92));
        bscs1a.enroll(new Student("Ben", 85));
        bscs1a.enroll(new Student("Cara", 78));
        bscs1a.printRoster();
    }
}

Output:

Section BSCS 1A (3 students)
  1. Ana
  2. Ben
  3. Cara
  Average: 85.00

Each class does its own job:

  • Student knows its own name and grade.
  • Section manages a group of students. To get a grade it asks each student through getGrade(), and never reaches into a Student's private fields.

This division of work, with each object responsible for its own data and asking other objects for theirs, is the heart of OOP design. It's also how you'll structure the Student Information Program in lab.

Quick check

In the example above, why does Section call students[i].getGrade() instead of reading students[i].grade?

Class relationships: has-a and is-a

Two relationships appear in almost every design:

RelationshipMeaningHow it's codedExample
has-a (composition)one object contains or uses anothera field of the other class's typea Section has Students; a Car has an Engine
is-a (inheritance)one class is a special kind of anotherclass Child extends Parenta Student is a Person; a Car is a Vehicle

A quick test: say the sentence out loud. "A section is a student" is false, but "A section has students" is true, so that's composition. You'll learn is-a (inheritance) in lesson 17.

In UML class diagrams, a has-a relationship is drawn as a line from the container to the part, often with a diamond on the container's end, and a number for "how many", such as 1 section to 0..40 students.

Quick check

Which pair is best modeled with composition (has-a)?

Common mistakes

  • Overloading by return type only: int total() and double total() won't compile.
  • Thinking parameter names make a new overload. Only types, number, and order count.
  • Reaching into another object's fields instead of calling its methods.
  • Forgetting to create the inner object: a Student[] field starts full of nulls, so check count before using an element.
  • Using inheritance for a has-a relationship, such as class Section extends Student.

Summary

  • A method's signature is its name plus its parameter types in order. Overloads must differ in parameters; names and return types don't count.
  • Objects are passed by copying the reference, so a method can update the caller's object.
  • Objects interact by calling each other's public methods.
  • Composition (a field of another class's type) models has-a; inheritance models is-a.

That completes the midterm topics. Next lesson: database basics and MySQL. After the database unit comes advanced OOP: inheritance, polymorphism, and abstraction.

References and further reading