CodeGym /Courses /JAVA 25 SELF /Class structure: fields, methods, constructors

Class structure: fields, methods, constructors

JAVA 25 SELF
Level 14, Lesson 2
Available

1. Class fields: where we store an object’s state

A field is a variable that is declared inside a class but outside all methods. Fields ensure each object has its own “state.” For example, if we have a class Person, the fields might be:

  • name — the person’s name
  • age — age
  • balance — account balance (if we’re building a banking app)
  • isStudent — a flag indicating whether our person is a student

Field declaration syntax

A field declaration looks like a regular variable, except it’s not inside a method—it’s directly in the class:

public class Person {
    String name;
    int age;
}

Here we declared two fields: a string name and an integer age. Each field belongs to a specific object of this class. That means different objects will have their own values. For example:

Person p1 = new Person();
p1.name = "Olya";
p1.age = 20;

Person p2 = new Person();
p2.name = "Igor";
p2.age = 25;

The first object’s name is “Olya” and age is 20, while the second’s is “Igor” and 25. They’re both made from the same class, but their fields hold different data.

Access modifiers (public/private)

Fields can be public (public) or private (private). In real life you don’t tell everyone your bank balance, right? Similarly, in programming fields are often private so other classes can’t access them directly. This is part of encapsulation (more on that later).

Example:

public class Person {
    private String name;
    private int age;
}

We won’t complicate things yet, but remember: if a field is private, you can’t access it directly from another class.

2. Class methods: how objects “act”

A method is a function that describes an object’s behavior. Methods let an object do things: speak, calculate, run, jump, print information about itself, and so on.

Method declaration syntax

return_type methodName(parameters) {
    // method body
}

Example of a method that says “Hello”:

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

Here:

  • public — the access modifier.
  • void — the method returns nothing (it just does something).
  • sayHello — the method name.
  • Inside the method we use the name field to greet the user.

Another example: a method that returns age

public int getAge() {
    return age;
}

Methods can return values (int, String, etc.), or they can “return nothing”—then we write void.

3. Constructors: how objects are “born”

A constructor is a special method that’s called when a new object is created. Its job is to initialize the object’s fields with initial values—that is, to fill the object’s “empty pockets” with concrete data. For example, set a person’s name and age right at creation time rather than leaving them empty.

  • The constructor name always matches the class name.
  • A constructor has no return type (you don’t even write void).
  • Constructors can take parameters (e.g., name and age) or have none.

Constructor example

public class Person {
    String name;
    int age;

    // Constructor with two parameters
    public Person(String name, int age) {
        this.name = name; // this.name — the object's field, name — the constructor parameter
        this.age = age;
    }
}

You’re probably wondering what this is. The this keyword is a reference to the current object—from the inside. We use it to distinguish a class field from a parameter with the same name. Without this, the compiler would be confused about what exactly we want to initialize.

Default constructor

If you don’t declare any constructor, the Java compiler automatically adds an empty no-arg constructor. It looks like this:

public Person() {
    // does nothing, but lets you create an object with no parameters
}

BUT! If you declare at least one constructor (for example, with parameters), the default constructor is no longer generated automatically! If you need it, write it explicitly.

4. Full class example

Let’s put it all together: fields, methods, constructor.

public class Person {
    String name;
    int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method: say hello
    public void sayHello() {
        System.out.println("Hello! My name is " + name + ", I am " + age + " years old.");
    }

    // Method: increase age by 1
    public void haveBirthday() {
        age = age + 1;
        System.out.println("Hooray! I am now " + age + " years old!");
    }
}

How do we use this in a program?

public class Main {
    public static void main(String[] args) {
        Person vasya = new Person("Vasya", 18);
        vasya.sayHello();      // Hello! My name is Vasya, I am 18 years old.
        vasya.haveBirthday();  // Hooray! I am now 19 years old!
    }
}

5. Practice: build out your application

Suppose you’re building a simple app for tracking users. In previous lessons we worked only with variables and methods inside main. Now let’s create our own User class with fields, methods, and a constructor.

public class User {
    String username;
    int score;

    // Constructor
    public User(String username, int score) {
        this.username = username;
        this.score = score;
    }

    // Method: print user info
    public void printInfo() {
        System.out.println("Username: " + username + ", points: " + score);
    }

    // Method: increase points
    public void addScore(int points) {
        score += points;
        System.out.println(username + " earned " + points + " points! Now they have " + score + " points.");
    }
}

Usage:

public class Main {
    public static void main(String[] args) {
        User alice = new User("Alice", 10);
        User bob = new User("Bob", 5);

        alice.printInfo(); // Username: Alice, points: 10
        bob.printInfo();   // Username: Bob, points: 5

        alice.addScore(7); // Alice earned 7 points! Now they have 17 points.
        bob.addScore(3);   // Bob earned 3 points! Now they have 8 points.
    }
}

Note: each object has its own fields, and changes to one object don’t affect another.

6. Briefly about access modifiers

In our examples the fields were accessible directly (String name;). In practice, fields are often made private so they can’t be changed accidentally (or intentionally) from another class. We’ll cover this in detail in encapsulation, but here’s an example:

public class User {
    private String username;
    private int score;

    public User(String username, int score) {
        this.username = username;
        this.score = score;
    }

    public void printInfo() {
        System.out.println("Username: " + username + ", points: " + score);
    }

    public void addScore(int points) {
        score += points;
    }
}

Now if someone tries to write alice.score = 100500; outside the class—the compiler will say “not allowed!”.

7. Typical mistakes when working with fields, methods, and constructors

Error #1: Uninitialized fields.
If you don’t assign values to fields, they get default values: numbers — 0, boolean — false, references (e.g., String) — null. If you forget to initialize a field, you can get an unexpected result or even a NullPointerException when you try to do something with it.

Error #2: Confusing parameters and fields.
In a constructor, beginners often write just name = name; — this doesn’t initialize the field; it simply assigns the parameter to itself. Always use this.name = name!

Error #3: No default constructor.
If you declared a constructor with parameters but forgot to add an explicit empty constructor, then new Person() will no longer work.

Error #4: Same names for methods and classes.
In Java a constructor’s name must match the class name, while methods must not. Sometimes people accidentally name a method the same as the class, and the compiler complains.

Error #5: Forgot about access modifiers.
If you make fields public, they can be changed anywhere—dangerous for large programs. It’s better to get used to private and use methods for access.

1
Task
JAVA 25 SELF, level 14, lesson 2
Locked
Dream Car on the Virtual Showcase
Dream Car on the Virtual Showcase
1
Task
JAVA 25 SELF, level 14, lesson 2
Locked
Quick registration of a new student
Quick registration of a new student
1
Task
JAVA 25 SELF, level 14, lesson 2
Locked
Digital event counter
Digital event counter
1
Task
JAVA 25 SELF, level 14, lesson 2
Locked
Bank Account Management
Bank Account Management
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION