HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to JavaVariablesData TypesOperatorsStringsArraysLists (ArrayList)Conditions (if / switch)Loops (for / while)MethodsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & List
🔁 Condition & Loop
🧩 Method & Class
Java›Classes (OOP)

Classes (OOP)

class, constructor, fields, methods, and creating objects with new.

Simple enough for a 5-year-old to understand

class and constructor

Example code
1
public class Main {
Executable class — comes FIRST.
DefinitionExecutable class — comes FIRST.
2
public static void main(String[] args) {
3
Cat k = new Cat("Tabby");
Create an object with new.
CodeCreate an object with new.
4
System.out.println(k.meow());
Tekir: meow
Output / InputTekir: meow
5
}
6
}
End of Main.
DefinitionEnd of Main.
7
class Cat {
Helper class (AFTER Main).
DefinitionHelper class (AFTER Main).
8
String name;
Field (property).
VariableField (property).
9
Cat(String name) {
Constructor (same name as class).
FunctionConstructor (same name as class).
10
this.name = name;
Assign the incoming name to the field.
VariableAssign the incoming name to the field.
11
}
12
String meow() {
Method.
FunctionMethod.
13
return name + ": meow";
14
}
15
}
End of Cat class.
DefinitionEnd of Cat class.
DefinitionCodeOutput / InputVariableFunction
💡 Hint: new Class(...) creates an object. Note: the executable "public class Main" file must be AT THE TOP; helper classes are written below it.

About this topic

A class is the grouping of related data and the behaviors that work with that data into a single structure. Since Java is an object-oriented language, classes are not an optional feature but the fundamental building block of the program — your main method was already inside a class.

A class is a blueprint, and an object is a concrete instance produced from that blueprint. You write a Cat class once and create as many cat objects from it as you want; each has its own name and age, but they all share the same behaviors.

Encapsulation is a strong tradition in Java: fields are made private, and access is provided through getter and setter methods. This prevents uncontrolled modification of the object's internal state and allows you to add validation later.

What you will learn

  • Defining classes and creating objects
  • Writing fields and the constructor method
  • When the this keyword is necessary
  • The logic of private, public, and encapsulation
  • Getter and setter methods
  • Overriding the toString method to produce readable output

When to use?

If you are constantly passing the same group of variables as parameters to a method, that group wants to be an object. If you are creating many instances of the same structure — users, orders, products — a class is the natural solution.

For classes that only carry data, modern Java versions have the record structure; it automatically generates the constructor, equality, and string representation, and is much shorter.

Common mistakes

Wrong

public class Cat {
    private String name;
    public Cat(String name) {
        name = name;
    }
}

Because the parameter and the field have the same name, the assignment assigns the parameter to itself; the field is never filled and remains null. Using this is mandatory to specify the field.

Correct

public class Cat {
    private String name;
    public Cat(String name) {
        this.name = name;
    }
}

Wrong

Cat c;
System.out.println(c.getName());

The variable has been declared but the object has not been created; object types start as null. Calling a method on null throws a "NullPointerException". You need to create the object with new.

Correct

Cat c = new Cat("Tabby");
System.out.println(c.getName());

Wrong

public class Cat {
    public List<String> toys = new ArrayList<>();
}

Making a field public allows anyone to directly modify the internal state of the object; you lose the ability to add validation or change the internal structure later. Fields should be private, and access should be through methods.

Correct

public class Cat {
    private final List<String> toys = new ArrayList<>();
    public void addToy(String t) {
        toys.add(t);
    }
}

Frequently asked questions

When does the constructor method run?

The moment the object is created with new, exactly once. It is used to assign initial values and perform necessary preparations. If you do not write a constructor, Java adds a parameterless default constructor; but the moment you write your own, the default disappears.

Why do we make fields private?

To protect the internal state of the object. Only the class's own methods access private fields; thus, you can prevent invalid values from being assigned, add validation later, and change the internal structure without breaking external code. This is called encapsulation.

Why should I override the toString method?

When you print an object with println, by default the class name and memory address are printed — which is useless when debugging. When you override the toString method and return meaningful text, you directly see the contents of the object.

Summary

A class combines data and behavior, while an object is the concrete instance created from it. Using this in the constructor, keeping fields private, and overriding the toString method are three essential habits in Java.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code