THINK FIRST·CODE LATER

← Java Programming
Chapter 10 · Week 1–3

Classes, Objects, and Encapsulation

Before You Start: What You Must Be Able to Do

Before the questions, make sure you can: explain what a class is and what an object is, and say what new actually does; write a class with private instance variables, accessors, mutators and ordinary instance methods; explain the calling object and what this refers to; say why an instance method cannot be called through the class name; distinguish an instance variable from a local variable and from a parameter; read and write a simple UML class diagram; and justify encapsulation in one sentence that is not “because the lecturer said so”.

Class and object

A class is a blueprint: it declares what data every object of that kind will hold (instance variables) and what every object of that kind can do (instance methods). An object is one concrete instance built from that blueprint, with its own copy of the instance variables. One Student class, three hundred Student objects, each with its own name and grade.

public class Student {              // the class: the blueprint
    private int    id;              // instance variables (fields, attributes)
    private String name;
    private double grade;

    public void setName(String name) { this.name = name; }     // mutator (setter)
    public String getName()          { return name; }          // accessor (getter)
    public boolean isPassed()        { return grade >= 50; }   // boolean method
    public void displayInfo() {                                // instance method
        System.out.println("ID: " + id + ", Name: " + name + ", Grade: " + grade);
    }
}

public class StudentApp {           // the driver class: it uses Student
    public static void main(String[] args) {
        Student s = new Student();  // creation: new allocates the object, s refers to it
        s.setName("Ali");           // s is the CALLING OBJECT of setName
        System.out.println(s.getName() + " " + s.isPassed());
    }
}

new Student() does three things: it allocates memory for a new object, it initialises the instance variables (explicitly or with their defaults), and it returns a reference to the object.

The calling object and this

In s.setName("Ali"), s is the calling object. Inside the method, this refers to that same object, so this.name is that student's name. this is needed whenever a parameter shadows a field — the almost universal case in a setter:

public void setGrade(double grade) { this.grade = grade; }  // field = parameter
public void setGrade(double grade) { grade = grade; }       // does nothing at all!

Instance variable, local variable, parameter

Declared Lives
Instance variable in the class body, outside every method as long as the object; gets a default value
Local variable inside a method until the method ends; no default, must be initialised
Parameter in the method heading until the method ends; initialised by the argument

Declaring int numOfItems = num; inside a method when a field numOfItems already exists creates a new local variable and leaves the field untouched. This is a classic exam trap.

Instance versus static in one sentence

An instance method needs an object because it works on that object's data; therefore ClassName.instanceMethod(...) does not compile, and main — which is static — must create an object before it can call one.

Encapsulation

Encapsulation means wrapping the data and the code that operates on it into a single unit, and exposing only what the outside world needs: fields private, behaviour public.

  • It protects data integrity: a mutator can reject a negative grade; a public field cannot.
  • It promotes usability: users of the class see a small, stable interface.
  • It allows the implementation to change without breaking callers.
  • It does not increase concurrency or improve performance — a distractor that has appeared on more than one exam paper.

UML class diagrams

A class is drawn as a three-part box: name, attributes, operations. - means private, + means public, # means protected, and the type follows a colon.

Student
- id : int
- name : String
- grade : double
+ getName() : String
+ setName(name : String) : void
+ isPassed() : boolean

Style conventions that are marked

Class names are nouns in UpperCamelCase; methods are verbs in lowerCamelCase; accessors begin with get, mutators with set, and boolean accessors with is. Fields go at the top or the bottom of the class consistently, each method does one thing, and a private helper method is preferred to a long method that repeats itself.

Remember
  • The class is the blueprint; the object is the instance.
  • Each object has its own copy of the instance variables.
  • this refers to the calling object and resolves shadowing.
  • An instance method requires an object; a static context does not have one.
  • private data plus public methods is encapsulation.
Common Pitfalls
  • name = name; in a setter instead of this.name = name;.
  • Re-declaring a field inside a method (int count = 0;) and wondering why the object never changes.
  • Calling an instance method from main without creating an object.
  • Making fields public “to keep things simple”.

Ready? Close the notes and practise.

38 questions. Predict the output before you check — that is the skill the exam measures.