Q1) Explain the four main principles of Object-Oriented Programming (OOP) with
examples.
Ans - Object-Oriented Programming (OOP) is a programming paradigm that organizes software
design around objects, which combine data and behavior. There are four core principles that
form the foundation of OOP:
1. Encapsulation
This is the concept of bundling data (variables) and methods (functions) that operate on the data
into a single unit called an object, and restricting access to some of the object's components.
Example:
Consider a BankAccount class. It can have private data like balance, and public methods like
deposit() and withdraw(). The balance cannot be modified directly; instead, you interact with it
through these methods.
2. Abstraction
Abstraction means hiding complex implementation details and showing only the necessary
features of an object. It helps reduce programming complexity.
Example:
When you use a Car object, you just call start() or drive(). You don't need to understand what
happens under the hood.
3. Inheritance
Inheritance allows a class (called a child or derived class) to inherit properties and behavior from
another class (parent or base class). This promotes code reuse.
Example:
A Dog class can inherit from a Animal class and reuse its methods.
4. Polymorphism
Polymorphism lets objects be treated as instances of their parent class, even if they behave
differently. It allows methods to do different things based on the object calling them.
Example:
Different shapes might implement a common draw() method differently
Q2) How does Object-Oriented Programming differ from Procedural Programming?
Provide examples.
Ans - Procedural Programming
This is a linear, step-by-step style of programming where the focus is on procedures or
routines (also called functions). It revolves around structured code execution, where data and
behavior are separate.
Key Characteristics:
• Uses functions to operate on data
• Data is generally global or passed around
• Emphasizes reusability through functions
• Easier to understand for small tasks
Object-Oriented Programming (OOP)
OOP emphasizes modeling real-world entities as objects. These objects bundle data and
behavior together and interact with each other.
Key Characteristics:
• Uses classes and objects
• Promotes encapsulation, inheritance, abstraction, and polymorphism
• Makes code modular, reusable, and easier to maintain for large projects
Q3) Describe the advantages of using OOP in software development.
Ans - 1. Modularity through Classes
OOP allows you to break down your code into self-contained objects (classes), each handling
specific tasks. This modularity makes large codebases easier to manage, test, and debug.
2. Reusability with Inheritance
Once you define a class, you can create new ones based on it without rewriting code. This lets
you build upon existing functionality, saving time and effort
3. Encapsulation for Security
By hiding internal object details and exposing only what’s necessary, encapsulation keeps your
data safe from unintended interference. It also reduces complexity for users interacting with
objects.
4. Polymorphism for Flexibility
Polymorphism enables you to write code that works on objects of different classes as long as
they share a common interface. This improves code flexibility and scalability, especially in large
systems.
5. Improved Maintainability
Because of encapsulation and modularity, updating and maintaining OOP code is often simpler.
Changes in one part of the program are less likely to affect others.
6. Real-World Modeling
OOP naturally maps to real-world scenarios by organizing code around objects that reflect
tangible concepts (like User, Account, or Invoice), making systems more intuitive and relatable.
7. Team Collaboration
OOP promotes clear responsibilities through classes and objects. This allows team members to
work independently on different modules without stepping on each other’s toes.
Q4) Explain the purpose of access specifiers (private, protected, public, and default) in Java
with examples.
Ans - 1. private – Strictly Personal
Accessible only within the same class. It keeps data hidden from the outside world to ensure
encapsulation.
Example:
class BankAccount {
private double balance; // can't be accessed directly outside this class
public void setBalance(double amt) {
balance = amt;
}
public double getBalance() {
return balance;
}
}
2. protected – Family and Friends
Accessible within the same package and by subclasses, even if they are in different packages.
Example:
class Animal {
protected void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
public void bark() {
sound(); // allowed because it's protected
}
}
3. public – Open to All
Accessible from anywhere—whether it’s from the same class, package, or a completely
different project.
Example:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
4. (default) – Package-Level Buddies
If no access specifier is mentioned, it's package-private by default—visible only within the
same package.
Example:
class Printer { // no specifier = default
void print() {
System.out.println("Printing...");
}
}
Q5) How does encapsulation improve security in object-oriented programming? Illustrate
with an example.
Ans - Encapsulation enhances security in Object-Oriented Programming by hiding the
internal state of an object and restricting direct access to it. Only specific, controlled
access is allowed through well-defined methods—this prevents unintended or malicious
interference.
Think of it like locking your valuables in a safe. You wouldn’t leave them on the table (public
access); instead, you keep them hidden and allow access only through a key or password
(getters/setters). This way, the integrity of the data remains intact.
Example: Securing Bank Balance
public class BankAccount {
private double balance; // Private: can't be directly accessed outside
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
Here’s what encapsulation is doing:
• balance is marked private: No external class can tamper with it directly.
• Interaction is allowed only through methods like deposit() and getBalance(), which
contain validation logic.
• This protects balance from accidental negative deposits or unauthorized edits.
Q6) What is method overriding in Java? How does it differ from method overloading?
Provide examples.
Ans - Method Overriding – Redefining Behavior in Subclasses
Definition: When a subclass provides its own specific implementation of a method that’s
already defined in its superclass.
• Same method name
• Same parameters (signature)
• Happens across classes via inheritance
Purpose: To achieve runtime polymorphism. It lets a subclass customize or specialize a
behavior.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
Method Overloading – Multiple Versions in the Same Class
Definition: When two or more methods in the same class have the same name but different
parameter lists (type, number, or order).
• Same method name
• Different parameters
• Happens within the same class
Purpose: To increase flexibility by allowing methods to handle different input combinations.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}}
Q7) What is the difference between String and StringBuffer in Java? Provide examples.
Ans - String – Immutable and Elegant
• A String object cannot be changed once it’s created.
• Every time you modify a String, a new object is created in memory.
• This immutability makes String safer for multithreaded operations but potentially less
efficient when dealing with lots of changes.
Example:
String str = "Hello";
str = str + " World"; // A new string object is created
System.out.println(str); // Output: Hello World
StringBuffer – Mutable and Efficient
• StringBuffer is mutable, meaning it can be changed without creating new objects.
• Designed for efficient manipulation when repeatedly modifying the same string.
• It is synchronized, making it thread-safe (but slightly slower than StringBuilder).
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies the same object
System.out.println(sb); // Output: Hello World
Q8) Write a Java program to demonstrate the usage of the StringBuilder class and its
advantages.
Ans - public class StringBuilderDemo {
public static void main(String[] args) {
// Initial string
StringBuilder sb = new StringBuilder("Java");
// Appending more text
sb.append(" is")
.append(" powerful")
.append(" and")
.append(" efficient.");
// Inserting a phrase
sb.insert(5, " programming");
// Replacing a word
sb.replace(25, 34, "fast");
// Reversing the entire string
sb.reverse();
// Output the final result
System.out.println("Final String (reversed): " + sb.toString());
}
}
Why Use StringBuilder Here?
• Performance Boost: No new string objects are created each time we modify the text.
• Method Chaining: Enables clean and fluent code.
• Reversibility & Flexibility: Built-in methods like insert(), replace(), reverse() offer fine
control
Q9) How can OOP principles be applied to solve real-world problems? Give an example of
an OOP-based application design.
Ans -
Object-Oriented Programming (OOP) shines when you're trying to model the complex,
interconnected systems we encounter in real life. It breaks down tangled problems into
manageable, reusable, and modular pieces—like giving every part of a machine its own brain
and personality. Let’s look at how each principle directly maps to real-world problem-solving:
Encapsulation: Protect the core, expose only what's necessary
In real life, you don’t control every part of a car—you just use the steering wheel and pedals.
Similarly, in OOP, classes expose only essential methods and hide inner workings.
Real-world example: A BankAccount class protects private data like balance, and you can only
access it through deposit() or getBalance() methods.
Abstraction: Hide the complexity behind simple interfaces
Think of turning on a light. You don’t need to understand the electrical engineering behind it. In
OOP, abstract classes and interfaces allow users to interact with systems at a higher level.
Real-world example: A Payment interface might have different implementations like
UPIPayment, CardPayment, or WalletPayment, but users just call pay().
Inheritance: Share common traits, specialize behavior
Much like how all birds have feathers, but not all birds fly, inheritance allows child classes to
inherit general behavior and customize it.
Real-world example: A Vehicle base class can be extended into Car, Bike, or Truck classes. They
all share common properties like speed or fuelType but implement their own unique features.
Polymorphism: One interface, many forms
You can plug different appliances into the same socket because they follow a shared interface.
Likewise, polymorphism allows different objects to be treated uniformly—even if their
behaviors differ.
Real-world example: A Shape interface may be implemented by Circle, Square, or Triangle. You
can loop through a list of Shape objects and call draw() without needing to know which shape it
is.
Q1) What is an instance variable? How is it different from a local variable in Java?
Ans - Instance Variable
An instance variable is a variable that’s declared inside a class, but outside any method,
constructor, or block. It belongs to an object, and each object gets its own copy of the variable.
Example:
public class Car {
// Instance variable
String color;
public Car(String c) {
color = c;
}
}
Local Variable
A local variable is declared inside a method or block and is accessible only within that scope.
It’s created when the method is called and destroyed when it finishes.
Example:
public void drive() {
// Local variable
int speed = 60;
System.out.println("Driving at " + speed + " km/h");
}
Q2) Explain the importance of this keyword in Java with an example.
Ans – This is a reference variable that points to the current object—the one whose method
or constructor is being called. It helps avoid ambiguity and ensures that object-specific
data is used where needed.
Why It’s Important:
1. Disambiguates between instance variables and parameters
2. Calls other constructors in the same class
3. Passes the current object as an argument
4. Returns the current object from a method
public class Student {
private String name;
// Constructor with parameter having the same name
public Student(String name) {
this.name = name; // 'this.name' refers to the instance variable
}
public void display() {
System.out.println("Student name: " + this.name);
}
public static void main(String[] args) {
Student s = new Student("Ayush");
s.display(); // Output: Student name: Ayush
}
}
Q3) Explain the types of constructors in Java with examples.
Ans –
1. Default Constructor
Provided automatically by Java if you don’t define any constructor. It initializes objects with
default values.
public class Bike {
String model;
// Default constructor (implicit if not defined)
public Bike() {
model = "Standard";
}
public void display() {
System.out.println("Model: " + model);
}
public static void main(String[] args) {
Bike b = new Bike(); // invokes default constructor
b.display(); // Output: Model: Standard
}
}
2. Parameterized Constructor
Takes parameters to initialize the object with custom values.
public class Student {
String name;
int age;
// Parameterized constructor
public Student(String n, int a) {
name = n;
age = a;
}
public void show() {
System.out.println(name + " is " + age + " years old.");
}
public static void main(String[] args) {
Student s = new Student("Ayush", 20);
s.show(); // Output: Ayush is 20 years old.
}
}
3. Copy Constructor (Not built-in like in C++, but can be defined manually)
Creates a new object by copying data from another object of the same class.
public class Book {
String title;
// Parameterized constructor
public Book(String t) {
title = t;
}
// Copy constructor
public Book(Book b) {
this.title = b.title;
}
public void print() {
System.out.println("Title: " + title);
}
public static void main(String[] args) {
Book original = new Book("Java Essentials");
Book copy = new Book(original);
copy.print(); // Output: Title: Java Essentials
}
}
4. Constructor Overloading
Multiple constructors with different parameter lists in the same class
public class Employee {
String name;
int id;
// No-arg constructor
public Employee() {
name = "Unknown";
id = 0;
}
// Parameterized constructor
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
}
Q5) Define encapsulation in Java. How does it help in data hiding?
Ans - Encapsulation in Java is the process of wrapping data (variables) and the code that
operates on that data (methods) into a single unit, typically a class. It's like putting
important documents in a locked folder and only giving access through a controlled
process.
How It Helps in Data Hiding
By declaring variables as private, you prevent direct access from outside the class. Instead,
controlled access is provided through public getter and setter methods. This keeps the internal
workings hidden and protects the data from unwanted changes.
Example
public class Employee {
// Private variable (hidden from outside)
private int salary;
// Public method to set salary
public void setSalary(int amount) {
if (amount > 0) {
salary = amount;
}
}
// Public method to get salary
public int getSalary() {
return salary;
}
}
Q6) What is abstraction in Java? How does it help in hiding implementation details?
Ans - Abstraction is the process of hiding internal implementation details and showing only
the essential features of an object. It's like using a remote—you press a button to change the
channel, but you don’t need to know how the circuitry works inside.
In Java, abstraction is primarily achieved in two ways:
• Using abstract classes
• Using interfaces
By interacting only with method signatures (not the actual logic), users of a class or system can:
• Focus on what an object does
• Ignore how it does it
This leads to simpler, cleaner, and more modular code.
interface Payment {
void pay(double amount); // abstract behavior
}
class CreditCardPayment implements Payment {
public void pay(double amount) {
System.out.println("Paid ₹" + amount + " using Credit Card.");
}
}
class UpiPayment implements Payment {
public void pay(double amount) {
System.out.println("Paid ₹" + amount + " using UPI.");
}
}
Q7) Write a Java program where an interface Vehicle is implemented by Car and Bike.
Ans - // Interface Vehicle
interface Vehicle {
void start();
void stop();
}
// Car implements Vehicle
class Car implements Vehicle {
public void start() {
System.out.println("Car is starting with a key...");
}
public void stop() {
System.out.println("Car has stopped.");
}
}
// Bike implements Vehicle
class Bike implements Vehicle {
public void start() {
System.out.println("Bike is starting with a kick...");
}
public void stop() {
System.out.println("Bike has stopped.");
}
}
// Main class to test
public class VehicleTest {
public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBike = new Bike();
System.out.println("Testing Car:");
myCar.start();
myCar.stop();
System.out.println("\nTesting Bike:");
myBike.start();
myBike.stop();
}
}
Q8) Write a Java program to create a Calculator class with methods for addition, subtraction,
multiplication, and division.
Ans- public class Calculator {
// Method to perform addition
public double add(double a, double b) {
return a + b;
}
// Method to perform subtraction
public double subtract(double a, double b) {
return a - b;
}
// Method to perform multiplication
public double multiply(double a, double b) {
return a * b;
}
// Method to perform division
public double divide(double a, double b) {
if (b == 0) {
System.out.println("Error: Division by zero!");
return Double.NaN;
}
return a / b;
}
// Main method for testing
public static void main(String[] args) {
Calculator calc = new Calculator();
double a = 10;
double b = 2;
System.out.println("Addition: " + calc.add(a, b));
System.out.println("Subtraction: " + calc.subtract(a, b));
System.out.println("Multiplication: " + calc.multiply(a, b));
System.out.println("Division: " + calc.divide(a, b));}}
Q9) Create a Car class with a constructor that initializes the brand and speed. Write a program
to create an object of this class.
Ans-public class Car {
// Instance variables
String brand;
int speed;
// Constructor to initialize brand and speed
public Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
// Method to display car details
public void displayInfo() {
System.out.println("Car brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
// Main method to test the Car class
public static void main(String[] args) {
Car myCar = new Car("Toyota", 120);
myCar.displayInfo();
}
}