Classes & Objects
The core of OOP! Learn how to define classes, create objects, and use constructors.
The core of OOP! Learn how to define classes, create objects, and use constructors. This hands-on tutorial focuses on practical implementation of classes & objects concepts.
Classes & Objects
Java is an Object-Oriented language. Everything consists of classes and objects.
What is a Class?
A class is a blueprint or a template for creating objects.
public class Car {
String color;
String model;
void drive() {
System.out.println("Vroom vroom!");
}
}
What is an Object?
An object is an instance of a class. If Car is the blueprint, then a specific red Ferrari is an object.
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // creating an object
myCar.color = "Red";
myCar.drive();
}
}
Constructors
A constructor is a special method used to initialize objects. It is called when an object of a class is created.
- Name must match the class name.
- No return type (not even
void).
public class Car {
String model;
// Constructor
public Car(String modelName) {
model = modelName;
}
public static void main(String[] args) {
Car myCar = new Car("Tesla");
System.out.println(myCar.model);
}
}
Interactive Code
Design your own Dog class!
AI Mentor
Confused about "Java classes, objects and constructors"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3What is a Class in Java?
Next Steps
Now that we have objects, let's learn the Four Pillars of OOP that make them powerful.