In this article, we will learn important OOP (Object-Oriented Programming) concepts in Java with real-world examples.
As we all know, Object-Oriented Programming concepts are very important. Without an idea of OOP concepts, you will not be able to design systems in an object-oriented programming model. It simplifies software development and maintenance.
Core OOPs Concepts:
- Object
- Class
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Let's discuss each OOP concept with a real-world example.
1. Object
An Object is a real-time entity having some state and behavior. In Java, an Object is an instance of the class having instance variables (state) and methods (behavior). The object of a class can be created by using the new
keyword in the Java Programming language.
A class is a template or blueprint from which objects are created. So, an object is the instance (result) of a class.
Various Definitions of an Object:
- An object is a real-world entity.
- An object is a runtime entity.
- An object is an entity that has a state and behavior.
- An object is an instance of a class.
Real-world examples:
- Dogs have states (name, color, breed, hungry) and behaviors (barking, fetching, wagging tail). Other examples include Chairs, Bikes, Markers, Pens, Tables, Cars, Books, Apples, Bags, etc. These can be physical or logical (tangible and intangible).
- Bicycles also have states (current gear, current pedal cadence, current speed) and behaviors (changing gear, changing pedal cadence, applying brakes).
Read more about Objects in Java with examples at What Is Object in Java with Programming Examples.
2. Class
A class is a group of objects that have common properties. It is a template or blueprint from which objects are created. In short, a class is the specification or template of an object.
Read more about Class in Java with examples at What is Class in Java with Programming Examples.
Real-world example: Circle
Let’s look at an example of a class and analyze its various parts in the below diagram. This example declares the class Circle
, which has the member variables x
, y
, and radius
of type Integer and the two member methods, area()
and fillColor()
.
The below diagram shows a Circle
class, which is a template for creating three objects:
3. Abstraction
Abstraction means hiding lower-level details and exposing only the essential and relevant details to the users.
Real-world examples:
- Car: A car abstracts the internal details and exposes to the driver only those details that are relevant to the driver's interaction with the car.
- ATM Machine: An ATM machine allows users to perform operations like cash withdrawal, money transfer, and retrieving mini-statements without knowing the internal details of the ATM.
Read more about Abstraction in Java with examples at Abstraction in Java with Example.
4. Encapsulation
Encapsulation is the process of wrapping data and methods in a single unit.
In OOP, data and methods operating on that data are combined together to form a single unit, which is referred to as a Class. Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safe from outside interference and misuse.
Real-world examples:
- Capsule: A capsule wraps different medicines inside it.
Read more at Encapsulation in Java with Example.
5. Inheritance
Inheritance is a process of obtaining the data members and methods from one class to another class. It is a fundamental feature of object-oriented programming.
Inheritance - IS-A relationship between a superclass and its subclasses.
- Super Class: The class whose features are inherited is known as a superclass (or a base class or a parent class).
- Sub Class: The class that inherits the other class is known as a subclass (or a derived class, extended class, or child class
). The subclass can add its own fields and methods in addition to the superclass fields and methods.
Real-world examples:
- Child and Parent: All the properties of a father are inherited by his son.
- Java Library: The extensive use of inheritance in the Java library. For example, the
Number
class abstracts various numerical (reference) types such asByte
,Integer
,Float
,Double
,Short
, andBigDecimal
.
Read more about Inheritance at Inheritance in Java with Example.
6. Polymorphism
Polymorphism is the process of representing one form in multiple forms.
Definitions of Polymorphism:
- Polymorphism allows us to perform a single action in different ways.
- Polymorphism allows you to define one interface and have multiple implementations.
- We can create functions or reference variables that behave differently in different programmatic contexts.
- Polymorphism means many forms.
Real-world example: Suppose if you are in a classroom at that time you behave like a student, when you are in the market at that time you behave like a customer, and when you are at home at that time you behave like a son or daughter. Here one person presents different behaviors in different contexts.
Read more at Polymorphism in Java with Example.
Apart from these core OOPs concepts, there are some other terms that are used in Object-Oriented design:
- Association
- Composition
- Aggregation
- Delegation
- Coupling
- Cohesion
Association
Definition: Association represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner.
Real-world example:
- Teacher and Student: A teacher can teach multiple students, and a student can be taught by multiple teachers. Both the teacher and student objects have their own lifecycle and can exist independently.
class Teacher {
private String name;
// constructor, getters, setters
}
class Student {
private String name;
// constructor, getters, setters
}
public class AssociationExample {
public static void main(String[] args) {
Teacher teacher = new Teacher("Mr. Smith");
Student student = new Student("John Doe");
// Association between teacher and student
}
}
Read more on Association in Java with Example.
Composition
Definition: Composition is a strong form of association where one class (the whole) contains another class (the part) and the part cannot exist without the whole.
Real-world example:
- Car and Engine: A car has an engine, and the engine cannot exist independently without the car.
class Engine {
private String type;
public Engine(String type) {
this.type = type;
}
// getters, setters
}
class Car {
private String model;
private Engine engine;
public Car(String model, Engine engine) {
this.model = model;
this.engine = engine;
}
// getters, setters
}
public class CompositionExample {
public static void main(String[] args) {
Engine engine = new Engine("V8");
Car car = new Car("Mustang", engine);
// Composition relationship
}
}
Read more on Composition in Java with Example.
Aggregation
Definition: Aggregation is a weak form of association where one class (the whole) contains another class (the part) but the part can exist independently of the whole.
Real-world example:
- Library and Books: A library contains books, but a book can exist independently of the library.
class Book {
private String title;
public Book(String title) {
this.title = title;
}
// getters, setters
}
class Library {
private String name;
private List<Book> books;
public Library(String name, List<Book> books) {
this.name = name;
this.books = books;
}
// getters, setters
}
public class AggregationExample {
public static void main(String[] args) {
Book book1 = new Book("1984");
Book book2 = new Book("To Kill a Mockingbird");
List<Book> books = Arrays.asList(book1, book2);
Library library = new Library("Central Library", books);
// Aggregation relationship
}
}
Read more on Aggregation in Java with Example.
Delegation
Definition: Delegation is a design pattern where an object expresses certain behavior to the outside but delegates responsibility for implementing that behavior to an associated object.
Real-world example:
- Ticket Booking: A travel agent delegates the responsibility of booking different types of tickets to specialized booking classes.
interface Booking {
void bookTicket();
}
class TrainBooking implements Booking {
@Override
public void bookTicket() {
System.out.println("Train ticket booked");
}
}
class FlightBooking implements Booking {
@Override
public void bookTicket() {
System.out.println("Flight ticket booked");
}
}
class BookingAgent {
private Booking booking;
public BookingAgent(Booking booking) {
this.booking = booking;
}
public void book() {
booking.bookTicket();
}
}
public class DelegationExample {
public static void main(String[] args) {
BookingAgent agent = new BookingAgent(new TrainBooking());
agent.book(); // Delegates booking to TrainBooking
agent = new BookingAgent(new FlightBooking());
agent.book(); // Delegates booking to FlightBooking
}
}
Read more on Delegation in Java with Example.
Coupling
Definition: Coupling refers to the degree to which one class knows about another class. Lower coupling is preferred to reduce dependencies between classes.
Real-world example:
- Electric Appliance and Plug: An electric appliance can be plugged into any socket without knowing the specifics of the electrical system.
class Plug {
public void plugIn() {
System.out.println("Plugged in");
}
}
class Appliance {
private Plug plug;
public Appliance(Plug plug) {
this.plug = plug;
}
public void use() {
plug.plugIn();
}
}
public class CouplingExample {
public static void main(String[] args) {
Plug plug = new Plug();
Appliance appliance = new Appliance(plug);
appliance.use();
}
}
Read more on Coupling in Java with Example.
Cohesion
Definition: Cohesion refers to the degree to which the elements of a module/class belong together. High cohesion is preferred as it indicates that a class has a well-defined responsibility.
Real-world example:
- ATM Machine: An ATM class should only handle operations related to ATM functions like withdrawing money, checking balance, etc.
class ATM {
public void withdrawMoney() {
// Code to withdraw money
}
public void checkBalance() {
// Code to check balance
}
}
public class CohesionExample {
public static void main(String[] args) {
ATM atm = new ATM();
atm.withdrawMoney();
atm.checkBalance();
}
}
Read more on Cohesion in Java with Example.
Conclusion
We have discussed the following OOPs concepts with real-world examples:
- Object
- Class
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
- Association
- Composition
- Aggregation
- Delegation
- Coupling
- Cohesion
References
- Abstraction in Java with Example
- Encapsulation in Java with Example
- Inheritance in Java with Example
- Polymorphism in Java with Example
- Composition in Java with Example
- Aggregation in Java with Example
- Association in Java with Example
- Cohesion in Java with Example
- Coupling in Java with Example
- Delegation in Java with Example
Looks like heading for Cohesion is written by mistake to "coupling"
ReplyDeleteYes. Thanks for reporting. Corrected!.
Deletenice one
ReplyDelete