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.
40 min•By Priygop Team•Last updated: Feb 2026
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
Example
// 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");
}
}Try It Yourself: Create a Dog Class
Try It Yourself: Create a Dog ClassJava
Java Editor
✓ ValidTab = 2 spaces
Java|40 lines|958 chars|✓ Valid syntax
UTF-8