Java OOP: Class and Object
Java OOP Concepts: Class and Object (Beginner Guide with Examples)
✨ Quick Summary
In this post, you’ll learn the basics of Object-Oriented Programming (OOP) in Java. We will cover what a Class is, what an Object is, how to create them, and understand OOP with simple real-life examples.
In our previous post, we learned about Java Methods and how to create reusable code.
Now it’s time to start the most important part of Java: Object-Oriented Programming (OOP).
Java is an OOP-based language, which means Java programs are built using:
- ✅ Classes
- ✅ Objects
- ✅ Methods
- ✅ Inheritance, Polymorphism, Encapsulation, Abstraction
In this post, we will start with the basics: Class and Object.
1) What is a Class?
A Class is like a blueprint or template. It defines what an object will have.
Example: A class is like a blueprint of a Car. The blueprint contains:
- Car name
- Car color
- Car model
- Car speed
But the blueprint is not a real car. It is just the design.
2) What is an Object?
An Object is the real thing created from a class.
Example: If class is Car, then objects can be:
- BMW
- Audi
- Tata
3) Example: Create a Class and Object in Java
class Student {
String name;
int age;
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class ClassObjectExample {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Aishwarya";
s1.age = 22;
s1.display();
}
}
4) Multiple Objects Example
You can create multiple objects from the same class.
class Car {
String brand;
String color;
void showCar() {
System.out.println("Brand: " + brand);
System.out.println("Color: " + color);
}
}
public class MultipleObjectsExample {
public static void main(String[] args) {
Car c1 = new Car();
c1.brand = "BMW";
c1.color = "Black";
Car c2 = new Car();
c2.brand = "Tata";
c2.color = "White";
c1.showCar();
System.out.println("-----");
c2.showCar();
}
}
5) Constructor (Introduction)
A Constructor is a special method used to initialize objects.
Constructor name is always the same as class name.
Example:
class Student {
Student() {
System.out.println("Constructor called!");
}
}
We will learn constructors in detail in the next post.
Conclusion
Class and Object are the foundation of Java OOP. Once you understand this, you can easily learn:
- ✅ Constructors
- ✅ Inheritance
- ✅ Polymorphism
- ✅ Encapsulation
- ✅ Abstraction
In the next post, we will learn about Java Constructors in detail with examples!
Good one
ReplyDeleteExactly right.
ReplyDelete