Classes & Objects
Classes are blueprints for creating objects. An object is an instance of a class that contains data (fields) and behavior (methods). This is the foundation of Object-Oriented Programming in Java. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
What are Classes and Objects?
A class is like a blueprint — it defines what properties (fields) and behaviors (methods) an object will have. An object is a specific instance created from that blueprint. For example, 'Car' is a class (blueprint), and 'myRedToyota' is an object (a specific car).
Creating Classes & Objects
// Defining a class
class Student {
// Fields (properties)
String name;
int age;
double gpa;
// Constructor — creates new Student objects
Student(String name, int age, double gpa) {
this.name = name;
this.age = age;
this.gpa = gpa;
}
// Methods (behaviors)
void introduce() {
System.out.println("Hi, I'm " + name + ", age " + age);
}
boolean isHonorStudent() {
return gpa >= 3.5;
}
void study(String subject) {
System.out.println(name + " is studying " + subject);
}
}
// Using the class
public class OOPDemo {
public static void main(String[] args) {
// Creating objects (instances)
Student alice = new Student("Alice", 20, 3.8);
Student bob = new Student("Bob", 22, 3.2);
// Using methods
alice.introduce();
bob.introduce();
System.out.println("Alice honor student: " + alice.isHonorStudent());
System.out.println("Bob honor student: " + bob.isHonorStudent());
alice.study("Java");
bob.study("Python");
}
}