Classes and Objects

First lesson of the Object-Oriented Java course, free to read: about 20 minutes, 3 exercises and 3 quiz questions. This is the catalogue's base lesson; in the student space, it is rewritten for your profile.

Objectives

  • Define a class with fields, a constructor, and methods
  • Create objects with new and call their methods
  • Understand this, references, and null

ClassesObjects and referencesConstructors

In the previous course, all your methods were static and data traveled through parameters. Object-oriented programming (OOP) brings data and the operations that manipulate it together in one place.

  • A class is a blueprint: “a bank account has a holder and a balance; you can deposit and withdraw money”.
  • An object is a concrete instance built from that blueprint: Ada’s account, Linus’s account.

Declaring a class

class CompteBancaire {
    // Fields (the state of each object)
    String titulaire;
    int solde;               // in euros for simplicity

    // Constructor: same name as the class, no return type
    CompteBancaire(String titulaire, int soldeInitial) {
        this.titulaire = titulaire;     // this.titulaire = field; titulaire = parameter
        this.solde = soldeInitial;
    }

    // Instance methods (no static): they act on THIS object
    void deposer(int montant) {
        solde += montant;
    }

    boolean retirer(int montant) {
        if (montant > solde) {
            return false;               // refused: insufficient balance
        }
        solde -= montant;
        return true;
    }

    @Override
    public String toString() {
        return "Account of " + titulaire + ": " + solde + " EUR";
    }
}

Creating and using objects

public class Main {
    public static void main(String[] args) {
        CompteBancaire a = new CompteBancaire("Ada", 100);   // new calls the constructor
        CompteBancaire b = new CompteBancaire("Linus", 20);
        a.deposer(50);
        boolean ok = b.retirer(30);           // false
        System.out.println(a);                // Account of Ada: 150 EUR (toString called)
        System.out.println(b.solde);          // 20
    }
}

Each object has its own field values: depositing into a changes nothing for b. Several classes can live in the same file, but only one can be public and it must carry the file’s name. If you run the file directly with java Main.java, put the Main class first: Java’s launcher (including Java 25) runs the first class declared in the file. In a real project, each class has its own file.

Multiple constructors

CompteBancaire(String titulaire) {
    this(titulaire, 0);       // calls the other constructor
}

If you write no constructor, Java provides a no-parameter constructor; as soon as you write one, that default constructor disappears.

References and null

A class-typed variable does not hold the object itself but a reference to it:

CompteBancaire c = a;      // c and a refer to the SAME object
c.deposer(10);
System.out.println(a.solde);  // 160: modified through c

CompteBancaire d = null;   // no reference
d.deposer(5);              // NullPointerException at runtime!

This is why == between two objects compares references, not content (we will see equals in lesson 5).

toString()

Every class inherits a toString() method that by default prints something like CompteBancaire@6d06d69c. Overriding it (@Override annotation) makes display and debugging much more pleasant.

In this first lesson, the fields are directly accessible (b.solde). This is convenient but dangerous: nothing stops you from writing b.solde = -1000. The next lesson fixes this problem with encapsulation.

Exercises

Solutions and tests stay on the server. In the student space, your code is run and checked, and the tutor gives hints before the solution.

  1. CodeDifficulty 1Server sandbox2 hints

    A Rectangle class

    Create a Rectangle class with two fields double largeur and hauteur, a constructor, the methods aire() and perimetre(), and a toString() that returns Rectangle 3.00 x 4.00. In main, read width and height and print:

    Rectangle 3.00 x 4.00
    Aire : 12.00
    Périmètre : 14.00

    Format with String.format(Locale.ROOT, "%.2f", ...) and read the numbers with Double.parseDouble(sc.next()).

    import java.util.Locale;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
        }
    }
    
    class Rectangle {
        // À compléter
    }
  2. CodeDifficulty 2Server sandbox2 hints

    Operations on an account

    Create the lesson’s CompteBancaire class (holder, integer balance, deposer, retirer which returns false if the balance is insufficient or the amount is negative, toString). The program reads:

    • a first line: the holder;
    • then lines D montant (deposit) or R montant (withdrawal) until the end of the input.

    For each refused withdrawal, print Refusé : <montant>. At the end, print Compte de <titulaire> : <solde> EUR. The initial balance is 0.

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String titulaire = sc.nextLine().trim();
        }
    }
    
    class CompteBancaire {
    }
  3. Multiple choiceDifficulty 21 hint

    References

    After CompteBancaire a = new CompteBancaire("Ada", 100); CompteBancaire c = a; c.deposer(50);, what is the value of a.solde?

    • 100
    • 150
    • 50

End-of-lesson quiz

  1. What does the new keyword do?

    • Declares a class
    • Creates an object and calls its constructor
    • Creates a static variable
  2. In a constructor, what does this.nom refer to?

    • The nom parameter
    • The nom field of the object being constructed
    • A global variable
  3. What happens when you call a method on a variable that is null?

    • The method returns null
    • A NullPointerException is thrown
    • Nothing

The rest of the course

  1. Encapsulation, Immutability, and Records20 min
  2. Inheritance, Abstract Classes, and Polymorphism20 min
  3. Interfaces, Sealed Types, and Pattern Matching20 min
  4. The Object Class: equals, hashCode, toString, and static Members20 min
  5. Generics and Composition: Designing an Object Model20 min

Object-Oriented Java · Intermediate · 4 h