Java Essentials: Classes and Objects
Classes Are Blueprints
A class is a blueprint that describes what an object looks like and what it can do. The blueprint lists fields, which store state, and methods, which define behavior. A single class can create many objects, and each object keeps its own copy of the fields.
public class Book {
private String title;
private int pages;
public Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
public String getTitle() {
return title;
}
public int getPages() {
return pages;
}
}This class declares two private fields so outside code cannot reach them directly. The constructor, which has the same name as the class, runs when an object is created. The this keyword refers to the current instance so the constructor parameters do not shadow the fields.
Creating Objects
The new keyword allocates memory and calls the constructor. Objects are created from a main method or from any other code that has access to the class.
Book novel = new Book("Dune", 412);
System.out.println(novel.getTitle());new Book("Dune", 412) builds one Book object. You can create as many as you like, and each one holds its own title and page count.
Encapsulation with Access Modifiers
Encapsulation is the practice of hiding internal state behind methods.
- private - only the class itself can access the member.
- public - any code can access the member.
- protected - the class, its package, and subclasses can access it.
- package-private - just the class and its package.
Getters return values and setters allow controlled updates. This gives you a place to validate input and to change internal behavior without breaking the code that calls you.
Key Points
- A class is a blueprint; an object is one concrete instance created with new.
- Fields store state and methods define behavior.
- Constructors use the class name and run at creation time.
- Access modifiers and getters support encapsulation.