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
thiskeyword - 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 themprivatemeans only code insideStudentcan touch them. - The constructor
Student(String name, int marks)has the class’s name and no return type. It runs when you writenew Student(...). this.name = name:thisrefers 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 countbelongs to the class, not to any one object, so it counts every student created.toString()decides whatSystem.out.println(s1)shows.@Overrideasks the compiler to check that you really are overriding a parent method.
Access Modifiers
| Modifier | Visible from |
|---|---|
private | The same class only |
| (none) | The same package |
protected | The same package and subclasses |
public | Everywhere |
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
- Giving the constructor a return type such as
void Student(). It then becomes an ordinary method that never runs onnew. - Forgetting
this.when a parameter shares the field’s name, so the field is never set. - Making every field public, which lets any code put an object into an invalid state.
- 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;
newcreates objects. - Constructors set up objects;
thisrefers to the current one. - Keep fields
privateand validate in setters. staticmembers belong to the class; overridetoString()for readable output.
