Multiple Objects and Classes

Objects Working Together

Example

Objects can hold other objects and arrays of objects. This is how real programs are built.

public class Main {
    public static void main(String[] args) {
        Course course = new Course("Java Basics", 3);
        course.enroll(new Learner("Asha", 92));
        course.enroll(new Learner("Imran", 78));
        course.enroll(new Learner("Lakshmi", 85));
        course.enroll(new Learner("Tom", 70));      // course is full
        course.report();
    }
}

class Learner {
    String name;
    int score;

    Learner(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

class Course {
    String title;
    Learner[] learners;
    int count = 0;

    Course(String title, int capacity) {
        this.title = title;
        this.learners = new Learner[capacity];
    }

    void enroll(Learner l) {
        if (count == learners.length) {
            System.out.println("Sorry " + l.name + ", " + title + " is full");
            return;
        }
        learners[count++] = l;
    }

    void report() {
        int total = 0;
        Learner top = learners[0];
        for (int i = 0; i < count; i++) {
            total += learners[i].score;
            if (learners[i].score > top.score) top = learners[i];
        }
        System.out.println(title + ": " + count + " learners, average " + total / count + ", topper " + top.name);
    }
}

Output

Sorry Tom, Java Basics is full
Java Basics: 3 learners, average 85, topper Asha

References Point to the Same Object

Example

public class Main {
    public static void main(String[] args) {
        Counter a = new Counter();
        Counter b = a;          // b refers to the SAME object
        a.increment();
        b.increment();
        System.out.println(a.value + " " + b.value);

        Counter c = new Counter();   // a new, separate object
        System.out.println(c.value);
        System.out.println(a == b);
        System.out.println(a == c);
    }
}

class Counter {
    int value;
    void increment() { value++; }
}

Output

2 2
0
true
false