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.
A Rectangle class
Create a
Rectangleclass with two fieldsdouble largeurandhauteur, a constructor, the methodsaire()andperimetre(), and atoString()that returnsRectangle 3.00 x 4.00. Inmain, read width and height and print:Rectangle 3.00 x 4.00 Aire : 12.00 Périmètre : 14.00Format with
String.format(Locale.ROOT, "%.2f", ...)and read the numbers withDouble.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 }Operations on an account
Create the lesson’s
CompteBancaireclass (holder, integer balance,deposer,retirerwhich returnsfalseif the balance is insufficient or the amount is negative,toString). The program reads:- a first line: the holder;
- then lines
D montant(deposit) orR montant(withdrawal) until the end of the input.
For each refused withdrawal, print
Refusé : <montant>. At the end, printCompte 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 { }References
After
CompteBancaire a = new CompteBancaire("Ada", 100); CompteBancaire c = a; c.deposer(50);, what is the value ofa.solde?- 100
- 150
- 50
End-of-lesson quiz
What does the new keyword do?
- Declares a class
- Creates an object and calls its constructor
- Creates a static variable
In a constructor, what does this.nom refer to?
- The nom parameter
- The nom field of the object being constructed
- A global variable
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
- Encapsulation, Immutability, and Records20 min
- Inheritance, Abstract Classes, and Polymorphism20 min
- Interfaces, Sealed Types, and Pattern Matching20 min
- The Object Class: equals, hashCode, toString, and static Members20 min
- Generics and Composition: Designing an Object Model20 min