Introduction to Object-Oriented Programming in Java
What is Object-Oriented Programming (OOP)?
Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects." Objects are
instances of classes, and they represent real-world entities or concepts. OOP is known for its ability to model
complex systems by breaking them down into smaller, reusable components.
Key Concepts of OOP in Java
Java is an object-oriented programming language, and it embodies several key concepts of OOP. Let's explore these
concepts in Java:
Classes and Objects
In Java, a class is a blueprint or template for creating objects. Objects are instances of classes and represent
specific entities. Here's a simple example of a class and object:
// Define a class
class Car {
String brand;
String model;
int year;
}
// Create an object
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.model = "Camry";
myCar.year = 2023;
Encapsulation
Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on that data within
a class. It helps in data hiding and controlling access to the object's internal state.
Inheritance
Inheritance allows a new class (subclass or derived class) to inherit properties and behaviors from an existing
class (superclass or base class). It promotes code reuse and establishes a hierarchy of classes.
// Superclass
class Vehicle {
String type;
void drive() {
System.out.println("Driving a " + type);
}
}
// Subclass
class Car extends Vehicle {
Car() {
type = "Car";
}
}
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It is achieved
through method overriding and interfaces, enabling flexibility and extensibility in the code.
// Superclass
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
// Subclasses
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}
Conclusion
Java's support for object-oriented programming makes it a powerful language for building robust and maintainable
software. You've been introduced to key OOP concepts in Java, including classes, objects, encapsulation, inheritance,
and polymorphism. As you delve deeper into Java development, these concepts will serve as the foundation for
building complex and scalable applications.