Java + Spring Boot track

Lesson 06 · Part 2: Object-Oriented Programming

Classes and Objects

Java is an object-oriented (OOP) language. Data is defined as a class, and an object (instance) is taken from the blueprint and used. In this section, you will see…

Part 2: Object-Oriented Programming3 min readFree lesson

Java is an object-oriented (OOP) language. Data is defined as a class, and an object (instance) is taken from the blueprint and used. In this section, you will see the most basic flow of defining a class, creating an object, and handling fields and methods.

Learning Objectives

  • Define a class with the class keyword
  • Distinguish between the roles of fields, methods, and constructors.
  • Know what this points to
  • Briefly see the effect of access limiters (public / private)

Key concepts

1) Class definition

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 behavior (methods).

2) Create object

Person p = new Person();
p.name = "exponent";
p.age = 21;
p.hello();

new creates an object in memory and stores its reference in the variable p.

3) Constructor

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 that has no return type. When creating an object, initial values ​​are received. If you do not define it separately, the compiler automatically adds a parameterless default constructor.

4) this keyword

this points to the current object itself. It is often used to clearly distinguish between parameter and field names when they are the same.

this.name = name;  //Left=field, right=parameter

See as example

Example 1 — Person.java: Class definition and object creation

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 = "exponent";
        p.age = 21;
        p.hello();
    }
}

Execution result

Hi, I'm Jisoo (21)

Memo: If the field is not initialized separately, the default value (0, null, false) is automatically given.

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("exponent", 21);
        PersonWithCtor b = new PersonWithCtor("Minsu", 25);
        System.out.println(a.name + ", " + a.age);
        System.out.println(b.name + ", " + b.age);
    }
}

Execution result

Index, 21
Minsu, 25

Note: The constructor is only called with new.

Example 3 — Counter.java: State by object

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);
    }
}

Execution result

c1=2, c2=1

Note: For different instances, fields are managed separately.

Example 4 — Rectangle.java: Adding behavior with a method

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("Circumference =" + r.perimeter());
    }
}

Execution result

area=12
Circumference=14

Memo: Bundling “data + methods that handle that data” into one class is the first step in OOP.

Common Mistakes

  1. Call like Person.hello() without creating an object (instance method requires an object)
  2. There is a conflict between field names and parameters, but this. is omitted → self-assigned
  3. If the constructor name is written incorrectly, it will be considered a method (no return type + class name must be the same)
  4. Declare and use only variables without new → NullPointerException
  5. Use == to compare object reference variables (object is usually .equals())

Cleanup

  • A class is a blueprint of state + behavior
  • The object is an instance taken from the class as new
  • The constructor is a method dedicated to object initialization.
  • this is the current object itself

Try it yourself

cd 02_object-oriented/06_class-and_object/src
javac Rectangle.java
java Rectangle

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/Counter.javaJava
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.javaJava
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 = "exponent";
        p.age = 21;
        p.hello();
    }
}
src/PersonWithCtor.javaJava
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("exponent", 21);
        PersonWithCtor b = new PersonWithCtor("Minsu", 25);
        System.out.println(a.name + ", " + a.age);
        System.out.println(b.name + ", " + b.age);
    }
}
src/Rectangle.javaJava
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("Circumference =" + r.perimeter());
    }
}

Assignment

Problem 1 — Book class

  • File name: Homework01.java
  • Core concepts: classes, constructors, methods

Requirements

  • Create class Book inside Homework01 or in the same file and have fields title, author, and pages.
  • In the constructor, we receive three values and initialize them.
  • The info() method returns a string in [Title] Author (number of pages) format.
  • In main, create two books and print the result info().

Expected output

[Effective Java] Joshua Bloch (page 384)
[Clean Code] Robert C. Martin (page 464)

Problem 2 — Circle Area

  • File name: Homework02.java
  • Core concepts: instance methods, Math.PI

Requirements

  • Define the double radius field, constructor, and area() method in class Circle.
  • Prints the area of circles with radii of 1, 2.5, and 3 to three decimal places.

Expected output

r=1.000 area=3.142
r=2.500 area=19.635
r=3.000 area=28.274

Check the correct answer

After solving it yourself, compare it with the reference solution below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

Homework01.javaJava
/** Define the Book class and output 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 + "page)";
    }
}
Homework02.javaJava
/** Circle area calculation.*/
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;
    }
}

Learn this lesson with a mentor

Work through the Java + Spring Boot track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now