06. Classes and Objects
Java is an object-oriented (OOP) language. You define data with a **class** and stamp out **objects (instances)** from that blueprint. This lecture covers defining a class and using its fields and methods through objects.
What you'll learn
- 1Define a class with the `class` keyword
- 2Distinguish fields, methods, and constructors
- 3Understand what `this` refers to
- 4See the effect of access modifiers (`public` / `private`)
Overview
Java is an object-oriented (OOP) language. You define data with a **class** and stamp out **objects (instances)** from that blueprint. This lecture covers defining a class and using its fields and methods through objects.
Core Concepts
1) Defining a class
public class Person {
String name;
int age;
void hello() {
System.out.println("Hi, I'm " + name);
}
}A class is a bundle of **state (fields)** and **behaviour (methods)**.
2) Creating an object
Person p = new Person();
p.name = "Jisoo";
p.age = 21;
p.hello();`new` allocates the object in memory, and its reference is stored in `p`.
3) Constructors
public class Person {
String name;
int age;
Person(String name, int age) { // constructor
this.name = name;
this.age = age;
}
}A constructor is a special method **with no return type** that initializes a new object. If you don't define one, the compiler adds a parameterless **default constructor**.
4) The `this` keyword
`this` refers to **the current object itself**. It's used to disambiguate when a parameter and a field share a name.
this.name = name; // left=field, right=parameterExamples
Example 1 β `Person.java`: define a class and create an object
public class Person {
String name;
int age;
void hello() {
System.out.println("Hi, I'm " + name + " (" + age + ")");
}
public static void main(String[] args) {
Person p = new Person();
p.name = "Jisoo";
p.age = 21;
p.hello();
}
}**Output**
Hi, I'm Jisoo (21)**Note:** uninitialized fields take the default value (0, null, false).
Example 2 β `PersonWithCtor.java`: constructor and `this`
public class PersonWithCtor {
String name;
int age;
PersonWithCtor(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
PersonWithCtor a = new PersonWithCtor("Jisoo", 21);
PersonWithCtor b = new PersonWithCtor("Minsu", 25);
System.out.println(a.name + ", " + a.age);
System.out.println(b.name + ", " + b.age);
}
}**Output**
Jisoo, 21
Minsu, 25**Note:** a constructor is only called via `new`.
Example 3 β `Counter.java`: per-instance state
public class Counter {
int count;
void increment() {
count++;
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
c1.increment();
c1.increment();
c2.increment();
System.out.println("c1=" + c1.count + ", c2=" + c2.count);
}
}**Output**
c1=2, c2=1**Note:** each instance has its **own** copy of the fields.
Example 4 β `Rectangle.java`: behaviour via methods
public class Rectangle {
int width;
int height;
Rectangle(int w, int h) {
this.width = w;
this.height = h;
}
int area() {
return width * height;
}
int perimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Rectangle r = new Rectangle(3, 4);
System.out.println("area=" + r.area());
System.out.println("perimeter=" + r.perimeter());
}
}**Output**
area=12
perimeter=14**Note:** bundling "data + methods that act on that data" into one class is the first step of OOP.
Full example code (src/)
src/Counter.java
public class Counter {
int count;
void increment() {
count++;
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
c1.increment();
c1.increment();
c2.increment();
System.out.println("c1=" + c1.count + ", c2=" + c2.count);
}
}
src/Person.java
public class Person {
String name;
int age;
void hello() {
System.out.println("Hi, I'm " + name + " (" + age + ")");
}
public static void main(String[] args) {
Person p = new Person();
p.name = "Jisoo";
p.age = 21;
p.hello();
}
}
src/PersonWithCtor.java
public class PersonWithCtor {
String name;
int age;
PersonWithCtor(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
PersonWithCtor a = new PersonWithCtor("Jisoo", 21);
PersonWithCtor b = new PersonWithCtor("Minsu", 25);
System.out.println(a.name + ", " + a.age);
System.out.println(b.name + ", " + b.age);
}
}
src/Rectangle.java
public class Rectangle {
int width;
int height;
Rectangle(int w, int h) {
this.width = w;
this.height = h;
}
int area() {
return width * height;
}
int perimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Rectangle r = new Rectangle(3, 4);
System.out.println("area=" + r.area());
System.out.println("perimeter=" + r.perimeter());
}
}
Common Mistakes
- Calling `Person.hello()` as if it were static β instance methods need an object
- Forgetting `this.` when a field and parameter collide β you assign to yourself
- Naming a constructor wrong (it must have no return type and match the class name)
- Using a variable without `new` β `NullPointerException`
- Comparing object references with `==` (usually use `.equals()`)
Summary
- A class is the **state + behaviour** blueprint
- An object is an instance stamped out via `new`
- A constructor exists only to initialize an object
- `this` refers to the current object
Practice
# Practice - 06. Classes and Objects
## Exercise 1 β `Book` class
- File: `Homework01.java`
- Key concepts: class, constructor, method
Requirements
- Define a `Book` class (in `Homework01` or alongside it) with fields `title`, `author`, `pages`.
- Initialize all three in the constructor.
- An `info()` method returns `[title] author(pages pages)`.
- In main create two books and print each `info()`.
Expected output
[Effective Java] Joshua Bloch(384 pages)
[Clean Code] Robert C. Martin(464 pages)## Exercise 2 β `Circle` area
- File: `Homework02.java`
- Key concepts: instance method, `Math.PI`
Requirements
- Class `Circle` with `double radius`, a constructor, and an `area()` method.
- Print the area for radii 1, 2.5, 3 to 3 decimal places.
Expected output
r=1.000 area=3.142
r=2.500 area=19.635
r=3.000 area=28.274## Solutions After trying it yourself, compare with [`answer/`](./answer/).
Solution code (homework/answer/)
answer/Homework01.java
/** Define a Book class and print info(). */
public class Homework01 {
public static void main(String[] args) {
Book a = new Book("Effective Java", "Joshua Bloch", 384);
Book b = new Book("Clean Code", "Robert C. Martin", 464);
System.out.println(a.info());
System.out.println(b.info());
}
}
class Book {
String title;
String author;
int pages;
Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
String info() {
return "[" + title + "] " + author + "(" + pages + " pages)";
}
}
answer/Homework02.java
/** Circle area. */
public class Homework02 {
public static void main(String[] args) {
double[] radii = {1.0, 2.5, 3.0};
for (double r : radii) {
Circle c = new Circle(r);
System.out.printf("r=%.3f area=%.3f%n", r, c.area());
}
}
}
class Circle {
double radius;
Circle(double radius) {
this.radius = radius;
}
double area() {
return Math.PI * radius * radius;
}
}
Try It Yourself
cd 02_oop/06_class/src
javac Rectangle.java
java RectangleNext Lecture
[07_Encapsulation](../07_μΊ‘μν/) β `private` fields, getters/setters, intro to `record`.
All lecture materials and example code are openly available on GitHub.
View on GitHub β