Classes and Objects
A class groups related fields together under one named type, and a constructor is a special method, named after the class, that runs automatically whenever you create a new instance with new. this.name = name inside the constructor assigns the parameter to the object's own field, disambiguating the two when they share a name.
Main.java
Try it yourself →public class Main {
static class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public static void main(String[] args) {
Person alice = new Person("Alice", 30);
System.out.println(alice.name + " is " + alice.age + " years old");
}
}Output
Alice is 30 years old
Next: encapsulation — private fields, getters, and why Java code almost always hides its fields behind methods.
Practice exercise
Define a class Book with fields title (String) and pages (int). Create a Book with title "Dune" and pages 412, then print title and pages using System.out.println(book.title + " " + book.pages).