Classes and Objects
💻 JavaModel real things with fields, constructors and methods.
Java is object-oriented. A class describes the data and behaviour of one kind of thing; an object is one instance.
- Create a class with fields and methods.
- Write constructors.
- Use encapsulation with getters.
A Class
Fields hold state. Methods define behaviour. Keep fields private so the class controls how they change.
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void addScore(int points) {
if (points > 0) {
score += points;
}
}
public String grade() {
if (score >= 70) return "A";
if (score >= 60) return "B";
if (score >= 50) return "C";
return "F";
}
}Using Objects
Create objects with new and call methods with dot notation.
Student student = new Student("Amina", 64);
student.addScore(8);
System.out.println(student.getName() + ": " + student.grade());Encapsulation
Private fields plus public methods let you change the internals later without breaking callers. Validation belongs inside the setter or constructor.
Practice
- Create a Book class with title, author and price.
- Add a method that returns a formatted description.
- Prevent a negative price in the constructor.
Hands-on exercise
Create a BankAccount class with:
1. A private balance.
2. A constructor that accepts an opening balance.
3. deposit and withdraw methods.
4. withdraw refuses to go below zero.
5. A getBalance method.
Recap
Classes group state and behaviour. Private fields with validated methods keep objects valid.
Example
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void addScore(int points) {
if (points > 0) {
score += points;
}
}
public String grade() {
if (score >= 70) return "A";
if (score >= 60) return "B";
if (score >= 50) return "C";
return "F";
}
}
Exercises
1. A private balance.
2. A constructor that accepts an opening balance.
3. deposit and withdraw methods.
4. withdraw refuses to go below zero.
5. A getBalance method.
Expected Output
1500.0 — the oversized withdrawal is refused.
Lesson Nav
Java Course
0/9 lessons completed
- 1 Getting Started with Java Tutorial
- 2 Variables and Data Types Tutorial
- 3 Conditions and Loops Tutorial
- 4 Methods and Parameters Tutorial
- 5 Arrays and ArrayLists Tutorial
- 6 Classes and Objects Tutorial
- 7 Inheritance, Interfaces and Polymorphism Tutorial
- 8 Exceptions and Files Tutorial
- 9 Project: A Console Grade Book Project