Java OOPs Concepts Made Simple: A Complete Beginner-Friendly Guide
Java OOPs Masterclass
Understand how real-world objects are represented using Object Oriented Programming in Java
Object Oriented Programming (OOPs) in Java - Complete Guide
Java is one of the most popular programming languages in the world. The main reason behind Java's popularity is its powerful Object Oriented Programming approach.
OOP allows developers to design applications by representing real-world entities as objects. It helps in writing code that is reusable, secure, maintainable, and easy to extend.
What is Object Oriented Programming?
Object Oriented Programming (OOP) is a programming paradigm that organizes code into objects, where objects are instances of classes.
In simple words, OOP allows us to combine:
- Data: Information related to an object (attributes/properties)
- Behavior: Actions performed by an object (methods/functions)
Simple Definition
OOP is a programming style where programs are designed using objects.
OOPs Concepts in Java
The four major pillars of Object Oriented Programming are:
- Polymorphism
- Abstraction
- Encapsulation
- Inheritance
Topics Covered in This Blog
Class and Object in Java
What is a Class?
A class is a blueprint or template that defines the structure and behavior of objects.
A class contains:
- Attributes: Represent properties or data of an object.
- Methods: Represent behaviors or actions performed by an object.
Class = Blueprint of Object
Object = Instance of Class
Real World Example 1: Registration Form
Imagine a blank registration form.
- A blank form without any information is similar to a Class.
- A filled form containing user details is similar to an Object.
Real World Example 2: Alarm Application
Consider the alarm application available on your smartphone.
The developers create an Alarm class. This class defines what every alarm should contain:
- Time
- Label
- Sound
- Enabled Status
It also defines actions that every alarm can perform:
- Ring
- Snooze
- Turn Off
The actual alarms created in your phone are objects. Examples:
- Wake Up Alarm
- Power Nap Alarm
- Pasta Timer
All these objects are created from the same class, but each object maintains its own independent data.
Class and Object Example Program
Let's create an Alarm class and create multiple objects from it. The class contains attributes to store data, methods to define behavior, and a constructor to initialize objects.
class Alarm {
// Attributes (State / Data)
String time;
String label;
boolean isEnabled;
int snoozeCount;
// Constructor
public Alarm(String time, String label) {
this.time = time;
this.label = label;
this.isEnabled = true;
this.snoozeCount = 0;
}
// Methods (Behavior)
public void ring() {
if(isEnabled)
System.out.println("BEEP BEEP! [" + time + "] - " + label);
else
System.out.println("... (Alarm for " + label + " is turned off)");
}
public void snooze() {
snoozeCount++;
System.out.println("Snoozed '" + label + "'. Total snoozes: " + snoozeCount);
}
public void toggle() {
isEnabled = !isEnabled;
System.out.println(label + " is now " + (isEnabled ? "ON" : "OFF"));
}
}
public class Main {
public static void main(String[] args) {
// Object 1
Alarm wakeUpAlarm = new Alarm(
"06:00 AM",
"Wake up for work"
);
// Object 2
Alarm powerNap = new Alarm(
"02:30 PM",
"20-Min Power Nap"
);
// Working with Object 1
wakeUpAlarm.ring();
wakeUpAlarm.snooze();
wakeUpAlarm.snooze();
System.out.println();
// Working with Object 2
powerNap.ring();
powerNap.toggle();
powerNap.ring();
}
}
Program Output
BEEP BEEP! [06:00 AM] - Wake up for work
Snoozed 'Wake up for work'. Total snoozes: 1
Snoozed 'Wake up for work'. Total snoozes: 2
BEEP BEEP! [02:30 PM] - 20-Min Power Nap
20-Min Power Nap is now OFF
... (Alarm for 20-Min Power Nap is turned off)
Understanding the Program
Alarm is a class that acts as a blueprint for creating alarm objects.
wakeUpAlarm and powerNap are two different objects created from the same Alarm class.
Both objects have the same behavior, but their data values are different.
Key Points to Remember
- A class is a blueprint used to create objects.
- An object is an instance of a class.
- A class defines attributes and methods.
- Attributes represent the state of an object.
- Methods represent the behavior of an object.
- Multiple objects can be created from the same class.
- Each object maintains its own independent data.
What's Next?
In the next section, we will explore:
- Data Hiding
- Abstraction
- Encapsulation
- Tightly Encapsulated Classes
Data Hiding in Java
In Object Oriented Programming, Data Hiding means preventing direct access to internal data from outside the class.
In simple words:
Outside code should not directly access or modify the internal data of an object.
Data hiding is achieved by declaring variables as private. The main advantage of data hiding is security.
Why Do We Need Data Hiding?
Imagine if any code could directly access your alarm object and modify its internal data.
- Someone could set snoozeCount = -500.
- Someone could change alarm time to an invalid value like 99:99 PM.
This can break the application logic. Therefore, we protect data and allow access only through controlled methods.
Data Hiding Example
class Alarm {
// Data Hiding: Variables are private
private String time;
private int snoozeCount;
public Alarm(String time) {
this.time = time;
this.snoozeCount = 0;
}
// Getter method
// Provides controlled access to read data
public int getSnoozeCount() {
return snoozeCount;
}
// Method with validation
// Controls how data can be modified
public void snooze() {
if(snoozeCount < 3) {
snoozeCount++;
System.out.println("Snoozed. Total snoozes: " + snoozeCount);
}
else {
System.out.println("Maximum snoozes reached! Time to wake up!");
}
}
}
public class Main {
public static void main(String[] args) {
Alarm myAlarm = new Alarm("06:00 AM");
// Direct access is not allowed
// myAlarm.snoozeCount = 100;
// Correct way of accessing data
myAlarm.snooze();
myAlarm.snooze();
myAlarm.snooze();
myAlarm.snooze();
System.out.println("Current snooze count: "+ myAlarm.getSnoozeCount());
}
}
Output
Snoozed. Total snoozes: 1
Snoozed. Total snoozes: 2
Snoozed. Total snoozes: 3
Maximum snoozes reached! Time to wake up!
Current snooze count: 3
Compiler Error Example
If we try to access a private variable directly:
myAlarm.snoozeCount = 100;
Error: snoozeCount has private access in Alarm
Because private members cannot be accessed outside their class.
Abstraction in Java
Abstraction means hiding internal implementation details and exposing only the required functionality to the user.
Abstraction = Showing what an object does while hiding how it does it.
In Java, abstraction can be achieved using:
- Abstract classes
- Interfaces
Real World Example: ATM Machine
When we use an ATM, we see simple options like:
- Withdraw money
- Deposit money
- Check balance
- Generate mini statement
But the ATM hides complex internal details such as:
- Which server processes the request
- How the database updates balance
- Which programming language is used internally
- How security validation happens
The user only knows the services provided by the ATM, not the internal implementation. This is abstraction.
Advantages of Abstraction
- Security: Internal implementation details are hidden from users.
- Easy Enhancement: Internal changes can be made without affecting outside users.
- Better Maintainability: Large applications become easier to manage and modify.
Encapsulation in Java
Encapsulation is the process of binding data and the methods that operate on that data into a single unit.
In Java, a class is the best example of encapsulation because it combines:
- Variables (Data)
- Methods (Behavior)
Encapsulation = Data Hiding + Abstraction
If a component follows both data hiding and abstraction, then that component is called an encapsulated component.
Encapsulation Example
class BankAccount {
private double balance;
public double getBalance() {
// Validation logic
return balance;
}
public void setBalance(double balance) {
// Validation logic
this.balance = balance;
}
}
Advantages of Encapsulation
- Security: Data is protected from unauthorized access.
- Control: We can control how data is accessed and modified.
- Maintainability: Changes inside the class do not affect outside code.
Disadvantage of Encapsulation
- Encapsulation increases the length of code because we need additional getter and setter methods.
- Due to additional method calls and validations, execution can become slightly slower.
Tightly Encapsulated Class in Java
A class is said to be tightly encapsulated if and only if every variable declared inside the class is private.
The following things are not required to check:
- Whether getter and setter methods are present or not.
- Whether getter and setter methods are declared public or not.
Rule: Every variable in the class must be declared private.
Example of Tightly Encapsulated Class
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
}
The above class is tightly encapsulated because the variable balance is private.
Question 1: Which Classes Are Tightly Encapsulated?
class A {
private int x = 10;
}
class B extends A {
int y = 20;
}
class C extends A {
private int z = 30;
}
Reveal Answer
Answer: A and C
Class A is tightly encapsulated because its variable is private.
Class C is also tightly encapsulated because its own variable is private.
Class B is not tightly encapsulated because it contains a non-private variable.
Question 2: Which Classes Are Tightly Encapsulated?
class A {
int x = 10;
}
class B extends A {
private int y = 20;
}
class C extends A {
private int z = 30;
}
Reveal Answer
Answer: No class is tightly encapsulated.
Although classes B and C contain private variables, they inherit from class A.
Class A contains a non-private variable, so it is not tightly encapsulated.
Important Rule: If the parent class is not tightly encapsulated, child classes are also not tightly encapsulated.
IS-A Relationship in Java (Inheritance)
IS-A Relationship is also known as Inheritance. It represents a relationship where one class inherits the properties and behaviors of another class.
Inheritance is implemented using the extends keyword in Java.
Main Advantage of Inheritance: Code Reusability
Why Do We Need Inheritance?
Imagine we have three classes:
class VehicleLoan {
// 300 methods
}
class HomeLoan {
// 300 methods
}
class PersonalLoan {
// 300 methods
}
Assume each method takes one hour to develop.
Total development time:
300 + 300 + 300 = 900 hours
Now imagine these three classes contain 250 common methods. Instead of writing the same methods repeatedly, we can create a parent class containing common functionality.
class Loan {
// 250 common methods
}
class VehicleLoan extends Loan {
// 50 specific methods
}
class HomeLoan extends Loan {
// 50 specific methods
}
class PersonalLoan extends Loan {
// 50 specific methods
}
Now the total development effort becomes:
250 common methods + 150 specific methods = 400 hours
Inheritance helps us achieve better code reusability.
Inheritance in Java API
The entire Java API is designed based on the concept of inheritance.
Object Class
The most common methods required for every Java object are defined inside the Object class.
Every class in Java is a child class of Object either directly or indirectly.
Object class acts as the root class for all Java classes.
Throwable Class
The Throwable class defines common methods required by all Exception and Error classes.
Throwable class acts as the root class for Java Exception hierarchy.
Types of Inheritance in Java
Java supports different types of inheritance:
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
- Multiple Inheritance
1. Single Inheritance
In single inheritance, a child class inherits from only one parent class.
Structure:
Parent Class → Child Class
Example
// Parent Class
class Phone {
void makeCall() {
System.out.println("Calling...");
}
}
// Child Class inherits Phone
class SmartPhone extends Phone {
void browseInternet() {
System.out.println("Browsing web...");
}
}
public class Main {
public static void main(String[] args) {
SmartPhone myPhone = new SmartPhone();
myPhone.makeCall();
myPhone.browseInternet();
}
}
Output
Calling...
Browsing web...
2. Multilevel Inheritance
In multilevel inheritance, a class inherits from another class which itself inherits from another class.
Structure:
Grandparent → Parent → Child
Example
// Grandparent Class
class Device {
void powerOn() {
System.out.println("Powering on...");
}
}
// Parent Class
class Phone extends Device {
void makeCall() {
System.out.println("Calling...");
}
}
// Child Class
class SmartPhone extends Phone {
void useApps() {
System.out.println("Opening app...");
}
}
public class Main {
public static void main(String[] args) {
SmartPhone myPhone = new SmartPhone();
myPhone.powerOn();
myPhone.makeCall();
myPhone.useApps();
}
}
Output
Powering on...
Calling...
Opening app...
3. Hierarchical Inheritance
In hierarchical inheritance, multiple child classes inherit from a single parent class.
Structure:
Child 1 - Parent Class - Child 2Example
// Parent Class
class Alarm {
void trigger() {
System.out.println("Alarm is ringing!");
}
}
// Child Class 1
class SoundAlarm extends Alarm {
void playSound() {
System.out.println("Playing loud siren...");
}
}
// Child Class 2
class LightAlarm extends Alarm {
void flashLights() {
System.out.println("Flashing bedroom lights...");
}
}
public class Main {
public static void main(String[] args) {
SoundAlarm sound = new SoundAlarm();
sound.trigger();
sound.playSound();
LightAlarm light = new LightAlarm();
light.trigger();
light.flashLights();
}
}
Output
Alarm is ringing!
Playing loud siren...
Alarm is ringing!
Flashing bedroom lights...
4. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance.
Java does not support hybrid inheritance using classes because it may create ambiguity. However, hybrid inheritance can be achieved using interfaces.
Example of Hybrid Inheritance
// Grandparent Class
class Device {
void powerOn() {
System.out.println("Powering on device...");
}
}
// Parent Class
class Phone extends Device {
void makeCall() {
System.out.println("Making a voice call...");
}
}
// Child Class 1
class SmartPhone extends Phone {
void useTouchScreen() {
System.out.println("Using touch screen...");
}
}
// Child Class 2
class FeaturePhone extends Phone {
void useKeypad() {
System.out.println("Using physical keypad...");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("--- SMARTPHONE ---");
SmartPhone smart = new SmartPhone();
smart.powerOn();
smart.makeCall();
smart.useTouchScreen();
System.out.println("--- FEATURE PHONE ---");
FeaturePhone feature = new FeaturePhone();
feature.powerOn();
feature.makeCall();
feature.useKeypad();
}
}
Output
--- SMARTPHONE ---
Powering on device...
Making a voice call...
Using touch screen...
--- FEATURE PHONE ---
Powering on device...
Making a voice call...
Using physical keypad...
5. Multiple Inheritance
Multiple inheritance means a child class inherits from multiple parent classes.
Java does not support multiple inheritance using classes because it creates the Diamond Problem.
What is Diamond Problem?
Consider two parent classes having the same method.
class A {
void display() {
System.out.println("Hello from A");
}
}
class B {
void display() {
System.out.println("Hello from B");
}
}
// Not allowed in Java
class C extends A, B {
}
Now if we create an object of class C and call:
c.display();
Java gets confused:
- Should it call method from Class A?
- Should it call method from Class B?
This ambiguity is called the Diamond Problem.
To avoid this problem, Java does not support multiple inheritance using classes.
Multiple Inheritance Using Interfaces
Java allows multiple inheritance through interfaces because interfaces do not create the same ambiguity.
// First Interface
interface Phone {
void takePhoto();
}
// Second Interface
interface Camera {
void takePhoto();
}
// Implementing Multiple Interfaces
class SmartPhone implements Phone, Camera {
public void takePhoto() {
System.out.println("Photo captured!");
}
}
public class Main {
public static void main(String[] args) {
SmartPhone phone = new SmartPhone();
phone.takePhoto();
}
}
Output
Photo captured!
Parent Reference and Child Reference in Java
In inheritance, a parent reference can hold a child object, but a child reference cannot hold a parent object.
Parent reference → Child object is allowed
Child reference → Parent object is not allowed
Example
class Parent {
void m1() {
System.out.println("Parent Method");
}
}
class Child extends Parent {
void m2() {
System.out.println("Child Method");
}
}
public class Main {
public static void main(String[] args) {
// Case 1
Parent p = new Parent();
p.m1();
// p.m2();
// Error: Parent reference cannot access child method
// Case 2
Child c = new Child();
c.m1();
c.m2();
// Case 3
Parent p1 = new Child();
p1.m1();
// p1.m2();
// Error: Parent reference cannot access child specific method
// Case 4
// Child c1 = new Parent();
// Error: Child reference cannot hold parent object
}
}
Important Rules of Inheritance
- A child class automatically gets access to the methods and variables of its parent class.
- Members available in the parent class are accessible by the child class.
- Child-specific members are not available through a parent reference.
- A parent reference can hold a child object.
- A child reference cannot hold a parent object.
Common Question About Object Class and Multiple Inheritance
Question:
Every class in Java implicitly extends the Object class. If my class explicitly extends another class, for example:
class Dog extends Animal {
}
Does this mean Java supports multiple inheritance?
Reveal Answer
No, it is not multiple inheritance.
It is called multilevel inheritance.
Difference Between Multiple and Multilevel Inheritance
Multiple Inheritance:
A single class has more than one direct parent class.
A B
\ /
C
Java does not support this using classes because of the Diamond Problem.
Multilevel Inheritance:
Classes are connected in a chain structure.
Object
|
Animal
|
Dog
Here:
- Object is the grandparent class.
- Animal is the parent class.
- Dog is the child class.
This is multilevel inheritance, not multiple inheritance.
How Java Handles Inheritance Hierarchy
Object - Animal - Dog
When a class does not explicitly extend any class, Java automatically makes it a child class of Object.
Therefore, every Java class gets common methods like:
- toString()
- equals()
- hashCode()
- getClass()
These methods are inherited from the Object class.
Complete OOPs Summary in Java
Object Oriented Programming helps us design programs using objects.
1. Class and Object
A class is a blueprint, and an object is an instance of that class. Classes define attributes and methods, while objects represent real-world entities.
2. Data Hiding
Data hiding protects internal data by restricting direct access. It is achieved using private variables.
3. Abstraction
Abstraction hides implementation details and exposes only required functionality. It improves security and maintainability.
4. Encapsulation
Encapsulation binds data and methods together into a single unit.
Encapsulation = Data Hiding + Abstraction
5. Inheritance
Inheritance allows one class to acquire properties and behaviors of another class. Its main advantage is code reusability.
Final Takeaway
Understanding OOP concepts is extremely important for becoming a strong Java developer. Almost every real-world Java application uses these concepts internally.
A strong understanding of:
- Classes and Objects
- Encapsulation
- Abstraction
- Inheritance
will help you understand advanced Java topics like Collections, Spring Framework, Hibernate, and enterprise application development.
🚀 Continue Your Java Learning Journey
Check out more beginner-friendly Java tutorials and complete roadmap articles.
Visit RoadmapForJava Blog
Comments
Post a Comment