0% found this document useful (0 votes)
2 views8 pages

Oop Questions

The document discusses the importance of Object-Oriented Programming (OOP), highlighting its benefits such as code organization, reusability, maintainability, and scalability. It explains key OOP concepts including the four pillars (encapsulation, inheritance, polymorphism, and abstraction), as well as method overloading and overriding, and the differences between static and dynamic polymorphism. Additionally, it covers abstract classes, their purpose, and the necessity of implementing abstract methods in subclasses.

Uploaded by

hashir.gdocs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Oop Questions

The document discusses the importance of Object-Oriented Programming (OOP), highlighting its benefits such as code organization, reusability, maintainability, and scalability. It explains key OOP concepts including the four pillars (encapsulation, inheritance, polymorphism, and abstraction), as well as method overloading and overriding, and the differences between static and dynamic polymorphism. Additionally, it covers abstract classes, their purpose, and the necessity of implementing abstract methods in subclasses.

Uploaded by

hashir.gdocs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Question 1: Why do we need OOP?

OOP allows us to model complex systems by representing real-world entities as


objects with data and behavior. We need OOP for:

Code organization - Breaking down complex systems into manageable parts


Reusability - Creating components that can be reused across projects
Maintainability - Making code easier to update and debug
Scalability - Allowing systems to grow while maintaining structure

Example: Instead of writing procedural code to manage a banking system, we can


create Account, Customer, and Transaction classes that better represent the real
system.
Question 2: What are the important pillars in OOP?
The four main pillars of OOP are:

Encapsulation - Bundling data and methods together, hiding internal details


Inheritance - Creating new classes based on existing ones
Polymorphism - Allowing objects to take different forms depending on context
Abstraction - Simplifying complex systems by modeling classes based on essential
properties

Question 3: What is a class and object?


A class is a blueprint or template that defines the structure and behavior of
objects. It specifies the attributes (data) and methods (functions) that objects of
that class will have.
An object is an instance of a class - a concrete entity created from the class
blueprint with its own unique data.
Example:
python# Class definition
class Car:
def __init__(self, make, model):
self.make = make
self.model = model

def drive(self):
return f"The {self.make} {self.model} is driving"

# Creating objects (instances of the Car class)


my_car = Car("Toyota", "Corolla")
your_car = Car("Honda", "Civic")

print(my_car.drive()) # Output: The Toyota Corolla is driving


Question 4: Abstraction vs Encapsulation?
Abstraction focuses on showing only essential features while hiding implementation
details. It helps manage complexity by providing a simplified interface.
Encapsulation bundles data and methods together and restricts direct access to some
components. It protects the internal state of an object.
Example:
java// Encapsulation
public class BankAccount {
private double balance; // Private variable - encapsulated

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
}
}

public double getBalance() {


return balance;
}
}

// Abstraction
public abstract class Vehicle {
// Abstract method - implementation details hidden
public abstract void accelerate();

// Concrete method
public void stop() {
System.out.println("Vehicle is stopping");
}
}
Question 5: Explain Inheritance?
Inheritance is a mechanism where a new class (subclass/derived class) can reuse,
extend, or modify the attributes and behaviors of an existing class
(superclass/base class). It promotes code reuse and establishes an "is-a"
relationship.
Example:
java// Parent/Base class
class Animal {
protected String name;

public Animal(String name) {


this.name = name;
}

public void eat() {


System.out.println(name + " is eating");
}
}

// Child/Derived class inheriting from Animal


class Dog extends Animal {
public Dog(String name) {
super(name);
}

public void bark() {


System.out.println(name + " is barking");
}
}

// Usage
Dog dog = new Dog("Rex");
dog.eat(); // Inherited method
dog.bark(); // Dog-specific method
Question 6: Explain virtual keyword?
The virtual keyword is used primarily in languages like C++ and C# to indicate that
a method can be overridden in derived classes. It enables runtime polymorphism
through method overriding.
Example (C#):
csharpclass Base {
public virtual void Display() {
Console.WriteLine("Display method from Base class");
}
}
class Derived : Base {
public override void Display() {
Console.WriteLine("Display method from Derived class");
}
}

// Usage
Base obj1 = new Base();
Base obj2 = new Derived();

obj1.Display(); // Output: Display method from Base class


obj2.Display(); // Output: Display method from Derived class (polymorphism)
Question 7: What is overriding?
Method overriding occurs when a subclass provides a specific implementation for a
method already defined in its parent class. The overridden method in the subclass
must have the same name, return type, and parameters as the method in the parent
class.
Example:
javaclass Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Cat says: Meow");
}
}

class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog says: Woof");
}
}
Question 8: Explain overloading?
Method overloading allows a class to have multiple methods with the same name but
different parameters (different number, types, or order of parameters). It's a
compile-time polymorphism.
Example:
javaclass Calculator {
// Overloaded methods
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;
}
}
Question 9: Overloading vs Overriding?
Overloading:
Same method name, different parameters
Occurs in the same class or in a subclass
Compile-time polymorphism
Method signature must differ (parameter types, count, or order)

Overriding:

Same method name, same parameters


Occurs in a subclass (parent-child relationship required)
Runtime polymorphism
Method signature must be identical

Question 10: What is polymorphism?


Polymorphism allows objects to behave differently based on context. It enables a
single interface to represent different underlying forms. There are two types:

Compile-time polymorphism (method overloading)


Runtime polymorphism (method overriding)

Example:
javaclass Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}

class Circle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a circle");
}
}

class Rectangle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}

// Polymorphic usage
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();

shape1.draw(); // Output: Drawing a circle


shape2.draw(); // Output: Drawing a rectangle
Question 11: Can polymorphism work without inheritance?
In most OOP languages, runtime polymorphism (method overriding) requires
inheritance. However, some forms of polymorphism can work without traditional
inheritance:

Interface implementation (not technically inheritance but achieves polymorphism)


Duck typing in languages like Python and JavaScript
Generics/Templates in languages like Java, C++

Example (Interface implementation in Java):


javainterface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a circle");
}
}

class Rectangle implements Drawable {


public void draw() {
System.out.println("Drawing a rectangle");
}
}

// Polymorphic usage through interfaces


Drawable shape1 = new Circle();
Drawable shape2 = new Rectangle();
Question 12: Explain static vs dynamic polymorphism?
Static Polymorphism (Compile-time):

Resolved at compile time


Method overloading is an example
Faster execution as binding occurs early
Less flexible

Dynamic Polymorphism (Runtime):

Resolved at runtime
Method overriding is an example
More flexible but slightly slower
Enables more extensible code

Example:
javaclass Calculator {
// Static polymorphism (overloading)
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}

class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


// Dynamic polymorphism (overriding)
@Override
public void makeSound() {
System.out.println("Dog says: Woof");
}
}
Question 13: Explain operator overloading?
Operator overloading allows operators (like +, -, *, /) to be redefined for user-
defined types. This makes custom types behave more like built-in types.
Example (C++):
cppclass Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}

// Overload + operator
Complex operator+(const Complex& obj) {
Complex result;
result.real = this->real + obj.real;
result.imag = this->imag + obj.imag;
return result;
}

void display() {
cout << real << " + " << imag << "i" << endl;
}
};

// Usage
Complex c1(3.0, 2.0);
Complex c2(1.0, 4.0);
Complex c3 = c1 + c2; // Using overloaded + operator
c3.display(); // Output: 4 + 6i
Question 14: How to do custom operator overloading?
The approach varies by language. Here's how to overload operators in Python and C+
+:
Example (Python):
pythonclass Vector:
def __init__(self, x, y):
self.x = x
self.y = y

# Overload + operator
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)

# Overload * operator (scalar multiplication)


def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)

# String representation
def __str__(self):
return f"Vector({self.x}, {self.y})"

# Usage
v1 = Vector(2, 3)
v2 = Vector(5, 1)
v3 = v1 + v2
v4 = v1 * 3

print(v3) # Output: Vector(7, 4)


print(v4) # Output: Vector(6, 9)
Question 15: Why do we need Abstract classes?
Abstract classes provide:

Partial implementation - Common functionality for subclasses


Blueprint enforcement - Force subclasses to implement certain methods
Common interface - Ensure subclasses adhere to a contract
Type hierarchy - Group related classes under a common type

Example:
javaabstract class DatabaseConnection {
// Common functionality
public void connect() {
System.out.println("Establishing connection...");
}

public void disconnect() {


System.out.println("Disconnecting...");
}

// Abstract method - must be implemented by subclasses


public abstract void executeQuery(String query);
}

class MySQLConnection extends DatabaseConnection {


@Override
public void executeQuery(String query) {
System.out.println("Executing MySQL query: " + query);
}
}

class PostgreSQLConnection extends DatabaseConnection {


@Override
public void executeQuery(String query) {
System.out.println("Executing PostgreSQL query: " + query);
}
}
Question 16: Are Abstract methods virtual?
Yes, abstract methods are implicitly virtual in most OOP languages. They must be
overridden in non-abstract derived classes.
In C#, for example:
csharpabstract class Shape {
// Abstract method is implicitly virtual
public abstract void Draw();

// Explicitly virtual method


public virtual void Resize() {
Console.WriteLine("Default resize behavior");
}
}

class Circle : Shape {


// Must implement the abstract method
public override void Draw() {
Console.WriteLine("Drawing a circle");
}

// Optional override of virtual method


public override void Resize() {
Console.WriteLine("Resizing the circle");
}
}
Question 17: Can we create an instance of Abstract classes?
No, you cannot create an instance of an abstract class directly. Abstract classes
are meant to be subclassed, and only instances of those concrete subclasses can be
created.
Example:
javaabstract class Vehicle {
protected String brand;

public Vehicle(String brand) {


this.brand = brand;
}

public abstract void drive();


}

class Car extends Vehicle {


public Car(String brand) {
super(brand);
}

@Override
public void drive() {
System.out.println("Driving " + brand + " car");
}
}

// This would cause a compilation error:


// Vehicle v = new Vehicle("Toyota");

// This is valid:
Vehicle v = new Car("Toyota");
v.drive(); // Output: Driving Toyota car
Question 18: Is it compulsory to implement Abstract methods?
Yes, it is compulsory for non-abstract subclasses to implement all abstract methods
inherited from their abstract parent classes or interfaces. If a subclass doesn't
implement all abstract methods, it must also be declared abstract.
Example:
javaabstract class Animal {
public abstract void makeSound();
public abstract void move();
}

// This abstract subclass doesn't need to implement all methods


abstract class Bird extends Animal {
@Override
public void move() {
System.out.println("Flying");
}
// makeSound() is still abstract
}

// Concrete class must implement all abstract methods


class Sparrow extends Bird {
@Override
public void makeSound() {
System.out.println("Chirp chirp");
}
// move() is already implemented in Bird
}

You might also like