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 methods | Overload allowed? | Why |
|---|---|---|
add(int a, int b) and add(double a, double b) | yes | different parameter types |
add(int a, int b) and add(int a, int b, int c) | yes | different number of parameters |
show(String s, int n) and show(int n, String s) | yes | different order of types |
add(int a, int b) and add(int x, int y) | no | parameter names don't count |
int total() and double total() | no | the 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: 65Java 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
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.0Inside 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,6Composition: 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.00Each class does its own job:
Studentknows its own name and grade.Sectionmanages a group of students. To get a grade it asks each student throughgetGrade(), and never reaches into aStudent'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
Class relationships: has-a and is-a
Two relationships appear in almost every design:
| Relationship | Meaning | How it's coded | Example |
|---|---|---|---|
| has-a (composition) | one object contains or uses another | a field of the other class's type | a Section has Students; a Car has an Engine |
| is-a (inheritance) | one class is a special kind of another | class Child extends Parent | a 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
Common mistakes
- Overloading by return type only:
int total()anddouble 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 ofnulls, so checkcountbefore 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.