Object-Oriented Programming (OOP) in Java
Understand how Java programs are organized using classes and objects. Learn constructors, encapsulation, inheritance, polymorphism and abstraction with simple explanations and practical examples.
Introduction to This Module
Imagine a school. It has students, teachers, classrooms and different activities. Each student has information such as name, age and roll number. Each student can also perform actions such as attending class or writing an exam.
Java uses a similar way of organizing programs. It groups information and actions together using classes and objects. This approach is called Object-Oriented Programming.
OOP makes programs easier to organize, reuse, maintain and expand. It is one of the most important topics for Java placement interviews.
What You Will Learn
- Understand Object-Oriented Programming.
- Learn the difference between classes and objects.
- Create constructors and understand their purpose.
- Use the this keyword in Java.
- Understand encapsulation and data hiding.
- Reuse code using inheritance.
- Understand method overloading and overriding.
- Learn abstraction using abstract classes and interfaces.
- Prepare for commonly asked OOP interview questions.
1. Introduction to Object-Oriented Programming
What Is OOP?
Object-Oriented Programming (OOP) is a way of writing programs by organizing code around objects.
An object represents something that has information and can perform actions.
Real-Life Example: A Car
Think about a car. A car has information such as its color, brand and speed. It can also perform actions such as starting, stopping and accelerating.
In Java, the information can be represented using variables, and the actions can be represented using methods.
What Are the Main Concepts of OOP?
Java mainly uses four important principles of OOP:
- Encapsulation: Keeping data and methods together and controlling access to data.
- Inheritance: Allowing one class to reuse the properties and methods of another class.
- Polymorphism: Allowing the same method name or reference to behave in different ways.
- Abstraction: Hiding implementation details and showing only essential functionality.
Why Do We Use OOP?
- It makes large programs easier to organize.
- It helps reuse existing code.
- It makes programs easier to maintain.
- It provides better control over data.
- It helps developers build applications that can grow over time.
2. Classes and Objects in Java
What Is a Class?
A class is a blueprint or design used to create objects. It describes what information an object will store and what actions it can perform.
Real-Life Example: House Blueprint
Before building a house, an architect may prepare a blueprint. The blueprint describes the rooms, doors and windows. Multiple houses can be built using the same blueprint.
Similarly, a Java class is a blueprint, and objects are the actual things created using that blueprint.
What Is an Object?
An object is an instance of a class. It represents an actual entity created using the class.
Creating a Class and Object
class Student {
String name;
int age;
void study() {
System.out.println(name + " is studying.");
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Rahul";
s1.age = 20;
System.out.println(s1.name);
System.out.println(s1.age);
s1.study();
}
}
Rahul 20 Rahul is studying.
Understanding the Code
class Studentcreates a class named Student.nameandageare variables of the class.study()is a method of the class.new Student()creates a new Student object.s1is a reference variable that refers to the object.- We use the dot operator to access the object's variables and methods.
Creating Multiple Objects
We can create multiple objects from the same class. Each object can store different information.
class Student {
String name;
int age;
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.name = "Rahul";
s1.age = 20;
s2.name = "Priya";
s2.age = 21;
System.out.println(s1.name + " " + s1.age);
System.out.println(s2.name + " " + s2.age);
}
}
Rahul 20 Priya 21
Class vs Object
| Class | Object |
|---|---|
| A blueprint or design. | An instance of a class. |
| Defines variables and methods. | Uses the variables and methods defined by the class. |
| Example: Student | Example: Rahul and Priya |
3. Constructors in Java
What Is a Constructor?
A constructor is a special member of a class that is used to initialize an object when it is created.
It is automatically called when we create an object using
the new keyword.
Important Features of Constructors
- A constructor has the same name as its class.
- It does not have a return type, not even
void. - It is called automatically when an object is created.
- It can have parameters.
- A class can have more than one constructor.
Example 1: Default Constructor Provided by Java
If we do not write any constructor in a class, Java provides a default constructor automatically.
class Student {
String name;
int age;
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(s1.name);
System.out.println(s1.age);
}
}
null 0
The instance variable name gets its default
value null, and age gets its
default value 0.
Example 2: Parameterized Constructor
A parameterized constructor accepts values when an object is created. These values can be used to initialize the object.
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student("Rahul", 20);
System.out.println(s1.name);
System.out.println(s1.age);
}
}
Rahul 20
Example 3: Constructor Overloading
Constructor overloading means creating multiple constructors in the same class with different parameter lists.
class Student {
String name;
int age;
Student() {
name = "Unknown";
age = 0;
}
Student(String n) {
name = n;
age = 18;
}
Student(String n, int a) {
name = n;
age = a;
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Rahul");
Student s3 = new Student("Priya", 21);
System.out.println(s1.name + " " + s1.age);
System.out.println(s2.name + " " + s2.age);
System.out.println(s3.name + " " + s3.age);
}
}
Unknown 0 Rahul 18 Priya 21
4. The this Keyword in Java
What Is this?
The this keyword refers to the current object.
It is commonly used when instance variables and method
parameters have the same names.
Simple Example
Imagine you have a notebook with your name written on it. When you say "this notebook", you are referring to the notebook that belongs to you.
In Java, this refers to the current object
whose method or constructor is executing.
Example Without this Keyword
Look at the following example. The parameter name and the
instance variable name are both name.
class Student {
String name;
Student(String name) {
this.name = name;
}
void display() {
System.out.println(name);
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student("Rahul");
s1.display();
}
}
Rahul
Understanding this.name = name
this.namerefers to the instance variable of the current object.- The second
namerefers to the constructor parameter. - The statement copies the parameter value into the object's variable.
Other Common Uses of this
- To refer to the current object's instance variables.
- To call another method of the same object.
- To call another constructor in the same class using
this(). - To pass the current object as an argument.
this() must be the first statement in that constructor.
5. Encapsulation and Data Hiding
What Is Encapsulation?
Encapsulation means combining data and the methods that operate on that data inside a single unit, usually a class.
In Java, encapsulation is commonly achieved by making
instance variables private and providing
public methods to access or update them.
Real-Life Example: ATM Machine
When you use an ATM, you can withdraw money or check your balance. However, you cannot directly access the internal system of the bank.
The ATM provides controlled operations instead of allowing direct access to its internal data. Encapsulation follows a similar idea.
What Is Data Hiding?
Data hiding means restricting direct access to an object's
internal data. In Java, we commonly use the
private access modifier for this purpose.
Example: Encapsulation
class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
}
}
public double getBalance() {
return balance;
}
}
class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(5000);
account.deposit(2000);
System.out.println("Balance = " + account.getBalance());
}
}
Balance = 7000.0
Understanding the Code
balanceis declared as private.- We cannot directly access it from the Main class.
- The
deposit()method provides controlled access to increase the balance. - The
getBalance()method returns the current balance.
Getters and Setters
A getter is a method used to read a private variable. A setter is a method used to update a private variable.
class Student {
private int age;
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
public int getAge() {
return age;
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.setAge(20);
System.out.println(s1.getAge());
}
}
20
6. Inheritance in Java
What Is Inheritance?
Inheritance is an OOP concept in which one class can acquire accessible fields and methods from another class.
It helps us reuse existing code instead of writing the same code again.
Real-Life Example
Imagine a general vehicle. It has common features such as a brand and a speed. A car and a bike are both vehicles, so they can share these common features.
In Java, we can create a parent class named Vehicle and child classes named Car and Bike.
Parent Class and Child Class
- Parent Class: The class whose accessible members are inherited.
- Child Class: The class that extends another class.
- extends: The keyword used to inherit a class.
Example: Single Inheritance
class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking.");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}
Animal is eating. Dog is barking.
The Dog class inherits the eat() method from
Animal and also has its own bark() method.
Types of Inheritance
Java supports these common class inheritance structures:
| Type | Meaning |
|---|---|
| Single Inheritance | One child class inherits from one parent class. |
| Multilevel Inheritance | A class inherits from a class that already inherits from another class. |
| Hierarchical Inheritance | Multiple child classes inherit from the same parent class. |
Example: Multilevel Inheritance
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
class Puppy extends Dog {
void play() {
System.out.println("Playing...");
}
}
class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat();
p.bark();
p.play();
}
}
Eating... Barking... Playing...
Does Java Support Multiple Inheritance?
Java does not allow a class to directly extend multiple classes. This avoids certain problems, such as ambiguity when two parent classes provide methods with the same name.
Java can achieve multiple inheritance of type through interfaces, which we will study in the abstraction topic.
extends to inherit
a class. A Java class can directly extend only one class,
but it can implement multiple interfaces.
7. Polymorphism – Method Overloading and Overriding
What Is Polymorphism?
Polymorphism means "many forms". In Java, it allows the same method name or a common reference type to work with different behaviors.
Real-Life Example
Imagine a person who can behave differently depending on the situation. At home, the person may be a parent. At work, the same person may be an employee.
Similarly, Java polymorphism allows different behavior through a common method name or reference.
Two Common Types of Polymorphism
- Compile-Time Polymorphism: Commonly achieved through method overloading.
- Runtime Polymorphism: Commonly achieved through method overriding.
A. Method Overloading
Method overloading means creating multiple methods with the same name but different parameter lists.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
}
class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(10, 20));
System.out.println(c.add(10, 20, 30));
System.out.println(c.add(5.5, 2.5));
}
}
30 60 8.0
B. Method Overriding
Method overriding happens when a child class provides its own implementation of an inherited instance method.
Example: Method Overriding
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks.");
}
}
class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
Dog barks.
Understanding Runtime Polymorphism
Animal adeclares a reference of type Animal.new Dog()creates a Dog object.- The reference points to the Dog object.
- Both classes have a method named
sound(). - Java executes the overridden method belonging to the actual Dog object.
Overloading vs Overriding
| Method Overloading | Method Overriding |
|---|---|
| Same method name with different parameter lists. | Child class provides a new implementation of an inherited method. |
| Usually happens within the same class. | Requires inheritance between classes. |
| Compile-time polymorphism. | Runtime polymorphism. |
| Return type alone cannot distinguish overloaded methods. | Return type must be compatible with the overridden method. |
8. Abstraction – Abstract Classes and Interfaces
What Is Abstraction?
Abstraction means hiding unnecessary implementation details and showing only the important features to the user.
Real-Life Example: Driving a Car
When you drive a car, you use the steering wheel, accelerator and brakes. You do not need to understand every internal detail of the engine to drive it.
The car provides the necessary controls while hiding much of its internal working. This is similar to abstraction in programming.
How Is Abstraction Achieved in Java?
Java mainly provides two ways to achieve abstraction:
- Abstract classes
- Interfaces
A. Abstract Classes
An abstract class is a class declared using the
abstract keyword.
It cannot be instantiated directly. It can contain both abstract methods and normal methods.
An abstract method is a method declared without a method body. A concrete child class must implement inherited abstract methods unless it is also abstract.
Example: Abstract Class
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Animal is sleeping.");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks.");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.sleep();
}
}
Dog barks. Animal is sleeping.
B. Interfaces
An interface defines a contract that implementing classes agree to follow.
It is declared using the interface keyword.
A class uses implements to implement an interface.
Interfaces can contain abstract methods, constants, and other supported method types such as default and static methods.
Example: Interface
interface Animal {
void sound();
}
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks.");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}
Dog barks.
Abstract Class vs Interface
| Abstract Class | Interface |
|---|---|
Declared using the abstract class keyword. |
Declared using the interface keyword. |
| Can have constructors. | Cannot have constructors. |
| Can have instance variables. | Fields are implicitly public, static and final. |
| Can contain abstract and concrete methods. | Can contain abstract, default, static and private methods, subject to Java version rules. |
| A class can extend only one class. | A class can implement multiple interfaces. |
abstract for abstract classes and
implements for implementing interfaces.
Also understand why a class can implement multiple interfaces.
9. Important OOP Concepts and Interview Questions
Quick Revision of the Four Pillars of OOP
| Concept | Simple Meaning | Java Feature |
|---|---|---|
| Encapsulation | Combining data and methods and controlling access. | Private variables and public methods. |
| Inheritance | Reusing accessible members from another class. | extends |
| Polymorphism | Different behaviors through common method names or references. | Overloading and overriding. |
| Abstraction | Hiding implementation details. | Abstract classes and interfaces. |
Important OOP Interview Questions
Q1. What is Object-Oriented Programming?
OOP is a programming approach that organizes code using classes and objects. It helps make programs reusable, organized and easier to maintain.
Q2. What is the difference between a class and an object?
A class is a blueprint that defines variables and methods. An object is an instance created using that class.
Q3. What is a constructor?
A constructor is a special member of a class that initializes an object when it is created.
Q4. Can a constructor be overloaded?
Yes. A class can have multiple constructors with different parameter lists.
Q5. What is the this keyword?
The this keyword refers to the current object. It is often used to distinguish instance variables from parameters having the same name.
Q6. What is encapsulation?
Encapsulation combines data and related methods inside a class and controls access to the data.
Q7. What is inheritance?
Inheritance allows a child class to acquire accessible members from a parent class.
Q8. Does Java support multiple inheritance?
Java does not support directly extending multiple classes. However, a class can implement multiple interfaces.
Q9. What is polymorphism?
Polymorphism allows different behaviors through the same method name or a common reference type. Method overloading and overriding are common examples.
Q10. What is the difference between overloading and overriding?
Overloading uses the same method name with different parameter lists. Overriding happens when a child class provides its own implementation of an inherited method.
Q11. What is abstraction?
Abstraction hides implementation details and shows only the important functionality.
Q12. Can we create an object of an abstract class?
No. We cannot directly create an object of an abstract class. We can create an object of a concrete child class.
Q13. What is an interface?
An interface defines a contract that classes can implement. It helps achieve abstraction and allows a class to implement multiple interfaces.
Q14. What is the difference between an abstract class and an interface?
An abstract class can have constructors, instance variables and concrete methods. An interface defines a contract and supports multiple implementation inheritance. Both can be used for abstraction.
Q15. Why is OOP important in Java?
OOP helps organize large programs, reuse code, control data access and make applications easier to maintain and extend.
Module Summary
- OOP organizes programs using classes and objects.
- A class is a blueprint, while an object is its instance.
- Constructors initialize objects when they are created.
- The this keyword refers to the current object.
- Encapsulation combines data and methods and controls access to data.
- Inheritance allows a child class to reuse accessible members of a parent class.
- Polymorphism allows different behaviors through common method names or references.
- Method overloading and overriding are important forms of polymorphism.
- Abstraction hides implementation details.
- Abstract classes and interfaces are used to achieve abstraction.
Practice Questions
Try these questions to check your understanding of Object-Oriented Programming.
- Create a Student class with name, age and a display method.
- Create two objects of a Car class and give them different details.
- Create a Student class with a parameterized constructor.
- Create a class with overloaded constructors.
- Write a program to demonstrate the this keyword.
- Create a BankAccount class using encapsulation.
- Write a program demonstrating single inheritance.
- Write a program demonstrating multilevel inheritance.
- Demonstrate method overloading using a Calculator class.
- Demonstrate method overriding using Animal and Dog classes.
- Create an abstract class and implement its abstract method.
- Create an interface and implement it in a class.
- Explain the four pillars of OOP with real-life examples.
Congratulations! Module 05 Completed
You have learned the major concepts of Object-Oriented Programming in Java. You now understand how to create classes and objects, initialize objects using constructors, protect data through encapsulation and reuse code through inheritance.
You have also learned polymorphism and abstraction, which are especially important for Java technical interviews.
Practice the coding examples and interview questions before moving to the next module.