Reading history

Java Classes and Objects: Constructors, this, Encapsulation

4 min read 0 views

Learn Java classes and objects: fields, constructors, the this keyword, private fields with getters and setters, static members and toString().

Java is an object-oriented language: almost everything lives inside a class. A class is a blueprint that defines the data (fields) and behaviour (methods) of a kind of thing, and an object is one actual thing created from it with new. This lesson builds a Student class with a constructor, private fields, getters and setters, a static counter and toString().

In this lesson you will learn

  • How to define a class with fields and methods
  • Constructors and the this keyword
  • Access modifiers and encapsulation
  • Static members shared by all objects
  • Overriding toString()

A Complete Class

class Student {
    private String name;
    private int marks;
    static int count = 0;

    Student(String name, int marks) {        // constructor
        this.name = name;
        this.marks = marks;
        count++;
    }

    String getName() { return name; }

    void setMarks(int marks) {
        if (marks < 0 || marks > 100) {
            System.out.println("Invalid marks: " + marks);
            return;
        }
        this.marks = marks;
    }

    String grade() { return marks >= 80 ? "A+" : marks >= 60 ? "A" : "B"; }

    @Override
    public String toString() { return name + " (" + marks + ")"; }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Rafi", 85);
        Student s2 = new Student("Nila", 64);
        s2.setMarks(120);
        s2.setMarks(81);
        System.out.println(s1 + " " + s1.grade());
        System.out.println(s2 + " " + s2.grade());
        System.out.println("Students created: " + Student.count);
    }
}

Output

Invalid marks: 120
Rafi (85) A+
Nila (81) A+
Students created: 2
  • Fields (name, marks) store each object’s data. Marking them private means only code inside Student can touch them.
  • The constructor Student(String name, int marks) has the class’s name and no return type. It runs when you write new Student(...).
  • this.name = name: this refers to the current object, so the field is set from the parameter with the same name.
  • The setter setMarks() validates input, which is why 120 was rejected. That control is the point of encapsulation.
  • static int count belongs to the class, not to any one object, so it counts every student created.
  • toString() decides what System.out.println(s1) shows. @Override asks the compiler to check that you really are overriding a parent method.

Access Modifiers

ModifierVisible from
privateThe same class only
(none)The same package
protectedThe same package and subclasses
publicEverywhere

A good default is to make fields private and expose only the methods other code needs.

Objects Are References

A variable such as s1 holds a reference to the object, not the object itself. Student s3 = s1; makes a second name for the same student, so changing marks through s3 also changes what s1 shows. A variable that refers to no object holds null, and calling a method on it throws NullPointerException.

Common Mistakes

  1. Giving the constructor a return type such as void Student(). It then becomes an ordinary method that never runs on new.
  2. Forgetting this. when a parameter shares the field’s name, so the field is never set.
  3. Making every field public, which lets any code put an object into an invalid state.
  4. Using a static field for per-object data, so every object shares one value.

Practice Exercises

Exercise 1. Create a Rectangle class with width, height, a constructor and area().

Show answer
class Rectangle {
    private final double width, height;
    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
    double area() { return width * height; }
}

Exercise 2. Add a second constructor Student(String name) that sets marks to 0.

Show answer
Student(String name) {
    this(name, 0);   // calls the other constructor
}

Frequently Asked Questions

What happens if I do not write a constructor?

Java adds a default no-argument constructor that sets fields to their default values. As soon as you write any constructor, that default is no longer added.

What is a record in Java?

A record (Java 16+) is a short way to declare a class that only holds data. Java writes the constructor, getters, equals(), hashCode() and toString() for you.

Summary

  • A class defines fields and methods; new creates objects.
  • Constructors set up objects; this refers to the current one.
  • Keep fields private and validate in setters.
  • static members belong to the class; override toString() for readable output.

Next: Java Inheritance and Polymorphism.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *