CodeGym /Courses /JAVA 25 SELF /The concept of a class and an object

The concept of a class and an object

JAVA 25 SELF
Level 14, Lesson 1
Available

1. What is a class and an object

Let’s start with an analogy. Imagine a car blueprint. The blueprint specifies that the car has four wheels, an engine, a color, seats, etc. But the blueprint itself doesn’t drive on roads, doesn’t make engine noise, and doesn’t need gasoline. It’s just a description of how the car is built.

A class in programming is the same kind of “blueprint” (or template) that defines what data (fields) and actions (methods) its instances will have.

An object is the “real” car assembled from that blueprint, a specific instance. Each object has its own state (for example, one car is red, another is blue) and behaviour: each object can perform the actions defined in the class (for example, drive, brake, honk).

Real-life examples

  • Class: Human (Person) — a description that a human has a name, age, height, and can speak or run.
  • Objects: Vasya, Petya, Katya — concrete people, each with their own name and age.
Class Object 1 Object 2
Person
name = "Vasya" 
age = 25
name = "Katya" 
age = 30

Why are classes important?

  • Group related variables and methods together.
  • Create as many objects as you want with the same structure but different data.
  • Easily describe complex entities: for example, “Bank account”, “Product”, “Book”, “User”.

2. Class declaration syntax

In Java, a class is declared using the keyword class. It’s followed by the class name (by convention — starting with a capital letter), and then curly braces that contain fields and methods.

A basic example

public class Person {
    // Fields and methods go here
}

Explanation:

  • public — an access modifier.
  • class — tells the compiler: “I declare a class”.
  • Person — the class name (you choose it yourself, but start with a capital letter).

Important rules for naming classes

  • The class name should start with a capital letter (for example, Car, Account, Book).
  • The class name must not contain spaces or special characters, except the underscore and $ (though this is rare).
  • If the name consists of multiple words, use CamelCase: BankAccount, BookStore.

Where do you write classes?

You can declare a class in a separate file (this is the usual approach: one file — one class) or inside another class (we’ll discuss nested classes later).

For example, the file Person.java:


public class Person {
    // fields and methods
}

3. Fields and methods of a class (briefly)

So far we’ve only declared a class, but it’s empty — like a box with no contents. Let’s add “properties” (fields) and “actions” (methods).

Fields (variables inside a class)

Fields describe what data each object of this class will have.


public class Person {
    String name; // person's name
    int age;     // age
}

Methods (functions inside a class)

Methods describe what an object can do.

public class Person {
    String name;
    int age;

    void sayHello() {
        System.out.println("Hello, my name is " + name + "!");
    }
}

Explanation:

  • void — the method returns nothing (we’ll talk about return values later).
  • sayHello() — the method name; parentheses are required.
  • Inside the method you can access the class fields (for example, name).

4. Creating an object

And now — magic! How do you turn the blueprint into a “real car”? Use the keyword new.

Syntax for creating an object


Person vasya = new Person();
  • Person — the variable type (our class).
  • vasya — the variable name (you can choose any).
  • new Person() — creates a new object of type Person.

Now we have a variable vasya that references an object of the Person class. This object has its own fields and methods.

Accessing fields and methods

Access fields and methods via the dot:

vasya.name = "Vasya";
vasya.age = 25;

vasya.sayHello(); // It will print: Hello, my name is Vasya!

You can create as many objects as you want

Person petya = new Person();
petya.name = "Petya";
petya.age = 30;

petya.sayHello(); // Hello, my name is Petya!

Each object is an independent “copy” with its own data.

5. Connection with previous topics

Before today’s lecture, we declared all variables and methods directly inside the class with the main method and didn’t think about creating our own types. Now we can create our own “containers” of data and functions.

This opens up huge possibilities! You can now describe any entities that appear in your task: customers, products, accounts, orders, animals, cars — anything at all. Programs become more structured, readable, and scalable.

Example: our first custom class

Let’s write a simple class for our mini program — say, “Bank account” (BankAccount). We will build on this example as the course progresses.

public class BankAccount {
    String owner;     // account owner
    int balance;      // account balance

    void printInfo() {
        System.out.println("Owner: " + owner + ", balance: " + balance + " euros.");
    }
}

Now in the main method (which is still required to run the program) we can create objects of this class:

public class Main {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount();
        account1.owner = "Ivan";
        account1.balance = 1000;
        account1.printInfo(); // Owner: Ivan, balance: 1000 euros.

        BankAccount account2 = new BankAccount();
        account2.owner = "Maria";
        account2.balance = 2000;
        account2.printInfo(); // Owner: Maria, balance: 2000 euros.
    }
}

Note: each object has its own field values. If you change the balance of account1, it won’t affect account2.

Visual diagram: class and objects

graph TD
    subgraph Class
        Person["Class Person | name:String | age:int | sayHello()"]
    end

    subgraph Objects
        vasya["vasya : Person | name = 'Vasya' | age = 20"]
        petya["petya : Person | name = 'Petya' | age = 25"]
    end

    vasya --> Person
    petya --> Person

Explanation:

  • Person — this is a class (a template).
  • vasya and petya — objects (instances) created from this template.

6. Common mistakes when declaring classes and creating objects

Error No. 1: Class name starting with a lowercase letter.
In Java it’s customary (the compiler won’t complain, but all experienced programmers will!) to name classes starting with a capital letter. Don’t write class person — write class Person.

Error No. 2: Missing curly braces.
Don’t forget that the class body must always be inside curly braces.

public class Person // error!
    String name;

Correct:

public class Person {
    String name;
}

Error No. 3: Trying to access class fields and methods without creating an object.
If a method or field is not declared as static, you can access it only via an object:

Person.sayHello(); // error!

Correct:

Person vasya = new Person();
vasya.sayHello();

Error No. 4: Mismatch between file name and class name (for a public class).
If a class is declared as public, the file name must match the class name:

// File Person.java
public class Person { ... }

If the file is named differently, the compiler will report an error.

Error No. 5: Using class variables without initializing an object.
Class fields (non-static) belong to the object, not to the class itself.

1
Task
JAVA 25 SELF, level 14, lesson 1
Locked
A new companion for your virtual world
A new companion for your virtual world
1
Task
JAVA 25 SELF, level 14, lesson 1
Locked
Bring a Purring Wonder to Life
Bring a Purring Wonder to Life
1
Task
JAVA 25 SELF, level 14, lesson 1
Locked
Creating a Digital Encyclopedia
Creating a Digital Encyclopedia
1
Task
JAVA 25 SELF, level 14, lesson 1
Locked
Opening a New Semester: Student Records
Opening a New Semester: Student Records
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION