Java objects combine state with behavior defined by a class. Constructors establish valid state, methods protect invariants, and encapsulation prevents unrelated code from changing fields arbitrarily.
Classes define state and behavior; objects carry concrete state whose validity should be established by constructors and protected by focused methods.
A field stores object state. A method defines behavior. Creating an object with new allocates an instance and lets you call its methods.
class Book {
String title;
String author;
void printDetails() {
System.out.println(title + " by " + author);
}
}
public class ObjectDemo {
public static void main(String[] args) {
Book book = new Book();
book.title = "Effective Java";
book.author = "Joshua Bloch";
book.printDetails();
}
}
A constructor initializes a new object. The this keyword refers to the current object and is often used to distinguish fields from parameters.
class Employee {
private String name;
private double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
void printSalary() {
System.out.println(name + ": " + salary);
}
}
Two objects can have the same field values but still be different objects in memory. Identity is about which object it is; state is about what values it holds.
class Point {
int x;
int y;
}
public class IdentityDemo {
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point();
p1.x = p2.x = 10;
p1.y = p2.y = 20;
System.out.println(p1 == p2); // false
}
}
A class is a blueprint and an object is a runtime instance created from that blueprint. Fields hold state, methods define behavior, and constructors prepare the object before it is used.
OOP basics in Java begin with a simple question: what thing does the program need to represent? A class is the blueprint for that thing, an object is one actual instance, fields store its state, and methods describe what it can do. This makes programs easier to organize than keeping unrelated variables and functions scattered everywhere.
Constructors matter because they create objects in a valid starting state. For example, a Student object should probably have a name before it is used. Methods should then operate on that object's own data. When this relationship between state and behavior is clear, later OOP topics become much easier.
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
boolean passed() {
return marks >= 40;
}
}
It should leave the new object in a valid state.
Private fields prevent callers from bypassing the rules enforced by the class.
No. Classes can also represent services, commands, policies, and technical boundaries.
Explore 500+ free tutorials across 20+ languages and frameworks.