Home Classes Objects Constructors this Keyword Encapsulation Static

Week 4: OOP - Classes, Objects, Constructors, Encapsulation

Liang Chapter 9: Defining Classes, Creating Objects, Constructors, Getters/Setters, the this Keyword, and Encapsulation

Defining Classes

A class is a template (blueprint) for creating objects. It defines the data fields (also called instance variables or properties) and methods that an object will have. An object is an instance of a class. (Liang, Ch. 9)

Class Structure

A class in Java can contain data fields (variables that store the state) and methods (functions that define the behavior). (Liang, Section 9.2)

public class Circle { // Data field (instance variable) double radius; // Method double getArea() { return radius * radius * Math.PI; } }

UML Class Diagram

In UML (Unified Modeling Language), a class is represented as a rectangle divided into three compartments: class name, data fields, and methods. (Liang, Section 9.2)

Circle
- radius: double
+ Circle()
+ Circle(newRadius: double)
+ getArea(): double
+ getPerimeter(): double
+ setRadius(radius: double): void
+ getRadius(): double

UML Notation

The - sign indicates private (accessible only within the class). The + sign indicates public (accessible from any class). (Liang, Section 9.2)

Class vs. Object

ClassObject
A blueprint or templateAn instance created from the class
Defined onceMultiple objects can be created
No memory allocated until an object is createdMemory is allocated when created with new
Example: Circle (the class)Example: myCircle (an object)
Q1: What is the relationship between a class and an object?
A) They are the same thing
B) A class is a blueprint; an object is an instance of a class
C) An object is a blueprint; a class is an instance
D) A class can only create one object
A class defines the structure and behavior. An object is a specific instance created from that class using the new keyword. You can create many objects from one class. (Liang, Section 9.2)
Q2: Which of the following is a correct class definition in Java?
A) public class Student { String name; }
B) class = Student { String name; }
C) def class Student { name: String; }
D) new class Student { String name; }
A Java class is defined with the class keyword, followed by the class name and a body in curly braces. Data fields are declared inside the class body. (Liang, Section 9.2)

Section Score

0 / 0

Creating and Using Objects

An object is created from a class using the new keyword. The new keyword invokes the class's constructor, allocates memory for the object, and returns a reference to it. (Liang, Section 9.3)

Creating Objects

Circle myCircle = new Circle(); myCircle.radius = 5.0; System.out.println("Area: " + myCircle.getArea());

Reference Variables

A variable that holds an object is actually a reference variable. It stores the memory address (reference) of the object, not the object itself. (Liang, Section 9.4)

Stack vs. Heap

Stack: Stores the reference variable (e.g., myCircle → address)

Heap: Stores the actual object (e.g., Circle object with radius: 5.0)

The reference on the stack points to the object on the heap.

Reference vs. Primitive

Primitive VariableReference Variable
Stores actual valueStores memory address of object
int x = 5;Circle c = new Circle();
Default: 0, false, etc.Default: null
Stored on the stackReference on stack, object on heap

Accessing Members

You access an object's data fields and methods using the dot operator (.). (Liang, Section 9.3)

Circle c1 = new Circle(); c1.radius = 10; // Access data field double area = c1.getArea(); // Call method System.out.println(area); // 314.159...

null and NullPointerException

If a reference variable does not point to any object, it holds the value null. Attempting to access a member through a null reference causes a NullPointerException. (Liang, Section 9.4)

Circle c = null; System.out.println(c.radius); // NullPointerException!
Q1: What does the new keyword do?
A) Declares a variable
B) Imports a class
C) Creates an object in memory and invokes the constructor
D) Deletes an existing object
The new keyword allocates memory on the heap for the object, invokes the constructor to initialize it, and returns a reference. (Liang, Section 9.3)
Q2: What is the default value of a reference variable?
A) 0
B) null
C) An empty object
D) undefined
The default value of a reference variable (when declared as a data field) is null, meaning it does not reference any object. (Liang, Section 9.4)

Trace the Code

Circle c1 = new Circle(); Circle c2 = c1; c1.radius = 5; c2.radius = 10; System.out.println(c1.radius);

What is the output? (Hint: c2 = c1 copies the reference, not the object)

Find the Bug

Circle myCircle; System.out.println(myCircle.getArea());
What is the error?
A) Variable myCircle might not have been initialized (no new was used)
B) Missing return type
C) getArea() doesn't exist
The variable myCircle is declared but never assigned an object with new Circle(). Local variables must be initialized before use. The compiler will report the error. (Liang, Section 9.4)

Section Score

0 / 0

Constructors

A constructor is a special method that is invoked to initialize an object when it is created using the new keyword. It has the same name as the class and no return type (not even void). (Liang, Section 9.5)

No-Arg Constructor

A constructor with no parameters is called a no-arg (no-argument) constructor. (Liang, Section 9.5)

public class Circle { double radius; // No-arg constructor public Circle() { radius = 1.0; } }

Parameterized Constructor

A constructor can take parameters to set initial values for the object's data fields. (Liang, Section 9.5)

public class Circle { double radius; // No-arg constructor public Circle() { radius = 1.0; } // Parameterized constructor public Circle(double newRadius) { radius = newRadius; } }

Constructor Overloading

A class can have multiple constructors with different parameter lists. This is called constructor overloading. Java determines which constructor to invoke based on the arguments passed. (Liang, Section 9.5)

Circle c1 = new Circle(); // Calls no-arg constructor (radius = 1.0) Circle c2 = new Circle(5.0); // Calls parameterized constructor (radius = 5.0)

Default Constructor

If you do not define any constructor in your class, Java automatically provides a default no-arg constructor that initializes data fields to their default values. However, if you define any constructor (even a parameterized one), Java does NOT provide the default no-arg constructor. (Liang, Section 9.5)

Complete Circle Class (Liang, Listing 9.9 Style)

public class Circle { double radius; public Circle() { radius = 1.0; } public Circle(double newRadius) { radius = newRadius; } double getArea() { return radius * radius * Math.PI; } double getPerimeter() { return 2 * radius * Math.PI; } } // Test program public class TestCircle { public static void main(String[] args) { Circle c1 = new Circle(); System.out.println("c1 area: " + c1.getArea()); Circle c2 = new Circle(5.0); System.out.println("c2 area: " + c2.getArea()); } }
Q1: What is the return type of a constructor?
A) void
B) The class type
C) int
D) Constructors have no return type (not even void)
A constructor does not have a return type — not even void. If you add a return type, it becomes a regular method, not a constructor. (Liang, Section 9.5)
Q2: If a class has a parameterized constructor but no no-arg constructor, what happens when you write new MyClass()?
A) Java uses the default constructor
B) Compilation error — no matching constructor found
C) The parameterized constructor is called with default values
D) Runtime error
Once you define any constructor, Java no longer provides the default no-arg constructor. You must explicitly define a no-arg constructor if you need one. (Liang, Section 9.5)

Trace the Code

Circle c1 = new Circle(); Circle c2 = new Circle(3.0); System.out.println(c1.radius + " " + c2.radius);

What is the output?

Section Score

0 / 0

The this Keyword

The keyword this refers to the current object — the object whose method or constructor is being invoked. It is commonly used to distinguish between data fields and parameters that have the same name. (Liang, Section 9.6)

Using this to Avoid Ambiguity

public class Circle { private double radius; public Circle(double radius) { this.radius = radius; // this.radius is the data field // radius is the parameter } }

Without this

If the parameter name is the same as the data field name, the parameter hides (shadows) the data field. Using this.radius explicitly refers to the data field. (Liang, Section 9.6)

Common Uses of this

UsagePurposeExample
this.fieldRefer to the current object's data fieldthis.radius = radius;
this.method()Call another method of the current objectthis.getArea();
this(args)Call another constructor from a constructorthis(1.0);

Calling One Constructor from Another

public class Circle { private double radius; public Circle() { this(1.0); // Calls Circle(double) constructor } public Circle(double radius) { this.radius = radius; } }

Rule

this(args) must be the first statement in the constructor. You cannot call it after other statements. (Liang, Section 9.6)

Q1: What does this refer to in a method?
A) The current object that invoked the method
B) The class itself
C) The previous object created
D) A static reference to the class
this is a reference to the current object — the one on which the method was called. (Liang, Section 9.6)

Find the Bug

public class Student { private String name; public Student(String name) { name = name; // Bug is here! } }

After new Student("Ali"), what is the value of the name field?

What is the problem?
A) "Ali" — it works correctly
B) null — the parameter shadows the field; should be this.name = name;
C) Compilation error
The assignment name = name assigns the parameter to itself. The data field is never set, so it remains null. The fix is this.name = name;. (Liang, Section 9.6)

Section Score

0 / 0

Encapsulation (Data Hiding)

Encapsulation is one of the fundamental OOP principles. It means making data fields private and providing public getter and setter methods to access and modify them. This protects the data from direct external access and enables data validation. (Liang, Section 9.9)

Why Encapsulation?

Benefits

Data protection: Prevents external code from setting invalid values directly.

Flexibility: The internal implementation can change without affecting external code.

Maintainability: Easier to debug and maintain — all access goes through methods.

Getters and Setters

A getter method returns the value of a data field. A setter method sets a new value, optionally with validation. (Liang, Section 9.9)

public class Circle { private double radius; // private data field public Circle() { radius = 1.0; } public Circle(double radius) { this.radius = radius; } // Getter public double getRadius() { return radius; } // Setter with validation public void setRadius(double radius) { if (radius >= 0) this.radius = radius; } public double getArea() { return radius * radius * Math.PI; } }

Naming Convention

For a data field xyz, the getter is getXyz() and the setter is setXyz(value). For a boolean field, the getter is isXyz(). (Liang, Section 9.9)

Access Modifiers Summary

ModifierClassPackageSubclassWorld
private
(default)
protected
public

Without vs. With Encapsulation

// ❌ Without Encapsulation Circle c = new Circle(); c.radius = -5; // Invalid! But no error — radius is now negative
// ✅ With Encapsulation Circle c = new Circle(); c.setRadius(-5); // Setter rejects negative value — radius stays 1.0 System.out.println(c.getRadius()); // 1.0
Q1: What is the main purpose of making data fields private?
A) To make the program run faster
B) To protect data and control access through methods
C) To prevent creating objects
D) To allow access from any class
Making data fields private prevents direct access from outside the class. Access is controlled through getter and setter methods, enabling validation. (Liang, Section 9.9)
Q2: What is the correct getter name for a boolean field called active?
A) getActive()
B) active()
C) isActive()
D) hasActive()
For boolean data fields, the JavaBeans convention uses is instead of get. So the getter is isActive(). (Liang, Section 9.9)

Find the Bug

public class TestCircle { public static void main(String[] args) { Circle c = new Circle(5.0); c.radius = 10.0; // Bug is here! } }
What is the error?
A) Compilation error: radius has private access in Circle
B) Runtime error
C) No error — it works fine
Since radius is declared private in the Circle class, it cannot be accessed directly from another class. You must use c.setRadius(10.0) instead. (Liang, Section 9.9)

Section Score

0 / 0

Static Members

A static variable or method belongs to the class, not to any particular object. It is shared by all objects of the class. (Liang, Section 9.7)

Static Variables

A static variable is shared among all instances of a class. If one object changes the static variable, all other objects see the updated value. (Liang, Section 9.7)

public class Circle { private double radius; private static int numberOfObjects = 0; // Shared by all public Circle() { radius = 1.0; numberOfObjects++; // Increment when a new object is created } public Circle(double radius) { this.radius = radius; numberOfObjects++; } public static int getNumberOfObjects() { return numberOfObjects; } }

Instance vs. Static

InstanceStatic
Belongs toEach objectThe class
AccessobjectName.memberClassName.member
MemoryOne copy per objectOne copy shared by all
ExampleradiusnumberOfObjects

Important Rules

• A static method cannot access instance variables or call instance methods directly.

• An instance method can access both static and instance members.

• A static method cannot use the this keyword. (Liang, Section 9.7)

Accessing Static Members

Circle c1 = new Circle(); Circle c2 = new Circle(5.0); System.out.println("Objects created: " + Circle.getNumberOfObjects()); // 2
Q1: Can a static method access an instance variable directly?
A) Yes, always
B) No — static methods belong to the class, not any specific object
C) Only if the variable is public
D) Only if using the this keyword
A static method does not belong to any particular instance, so there is no this and no way to access instance variables directly. It can only access static members. (Liang, Section 9.7)
Q2: How should you call a static method?
A) Using the class name: ClassName.methodName()
B) Using this.methodName()
C) Static methods cannot be called
D) Only from the main method
Static methods should be called using the class name for clarity: ClassName.methodName(). While calling through an object reference works, it is misleading and not recommended. (Liang, Section 9.7)

Trace the Code

Circle a = new Circle(); Circle b = new Circle(2.0); Circle c = new Circle(3.0); System.out.println(Circle.getNumberOfObjects());

What is the output?

Find the Bug

public class Circle { private double radius; public static double getArea() { return radius * radius * Math.PI; } }
What is the error?
A) Cannot access instance variable radius from a static method
B) Missing return statement
C) Wrong return type
getArea() is static but tries to access radius, which is an instance variable. A static method cannot reference instance variables. Remove the static keyword to fix. (Liang, Section 9.7)

Section Score

0 / 0

Week 4

Defining Classes Creating Objects Constructors this Keyword Encapsulation Static Members