0% found this document useful (0 votes)
25 views17 pages

Oops

Uploaded by

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

Oops

Uploaded by

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

1. What is Object-Oriented Programming?

Object-Oriented Programming (OOPS) is a programming style where we


organize code into objects, which represent real-world entities like
a person, car, or bank account. These objects have properties (called
attributes) and actions (called methods).
The main idea is to model our programs closer to how we understand
things in real life. For example, a Car has properties like color,
model, and speed, and actions like drive() and brake(). OOPS helps in
making the code modular, reusable, and easier to manage as the
project grows.
Key languages like Java, C++, Python support OOPS.

2. What are the main principles of OOPS?

OOPS is built on four key principles, often called the pillars of


OOPS:

 Encapsulation: Wrapping data and methods into one unit, like a


capsule hiding its medicine. It protects data from unauthorized
access.

OOPS  Abstraction: Showing only necessary details, hiding the


complexity. Like how we use a TV remote without knowing its
circuit design.

 Inheritance: Reusing features of one class in another. Like a

Interview Questions child inherits qualities from parents.

 Polymorphism: One action behaving differently. For example, a


person behaves differently at home and at work.
These principles help to write cleaner, reusable, and more
organized code.

3. Define class and object with examples.

 A class is like a blueprint or design. It describes what an


object will contain and do. Example: A class called Car can have
properties like color and speed, and methods like drive() and
brake().

 An object is the real-world entity created from the class. For


example, Car car1 = new Car(); creates an object car1 which has
color and speed.
In short, the class is the plan, and the object is the actual Example: A Dog class inherits from Animal class. Dog has its own
thing created from the plan. features but also shares general features of animals.

Types of inheritance:

4. What is the difference between a class and an object?  Single: One child inherits from one parent.

 Class: Blueprint, design, or template. It doesn’t occupy memory.  Multilevel: Child inherits from parent, and that parent from
Example: Car design. another.

 Object: Actual instance of the class. It occupies memory.  Hierarchical: Multiple children inherit from one parent.
Example: Your red Maruti Swift car.
 Multiple (C++ supports, Java doesn’t): Child inherits from
Class describes the structure and behavior, while an object is a
multiple parents.
real entity having those characteristics. You can create
multiple objects from one class, just like multiple cars from  Hybrid: Combination of two or more inheritance types.
one car design.

8. What is Polymorphism?
5. Explain Encapsulation with a real-world example.
Polymorphism means "many forms." It allows a single action to behave
Encapsulation means hiding the internal data of a class and allowing differently in different situations.
access only through methods. It protects data from being modified Example: A print() function might print integers, strings, or
directly. floating numbers differently but uses the same method name.
For example, in a Bank Account, you don’t access the balance
There are two types:
directly. You use methods like deposit() and withdraw() which follow
some rules.  Compile-time (Static) Polymorphism: Method overloading, operator
In programming, you make variables private and allow access overloading.
through public getter and setter methods. This way, you control how
the data is accessed and changed.  Run-time (Dynamic) Polymorphism: Method overriding using
inheritance.

6. What is Abstraction? Give an example.


9. What is the difference between Overloading and Overriding?
Abstraction means showing only important features and hiding complex
details.  Overloading: Same method name but different parameter lists
For example, when you drive a car, you use the steering wheel and within the same class. It happens at compile-time.
pedals. You don’t know how the engine or brakes work internally. Example: add(int a, int b) and add(float a, float b).
In programming, abstraction is achieved using abstract classes or  Overriding: Same method name and parameters in parent and child
interfaces where you define what should be done but hide how it is classes. Child provides its own implementation. It happens at
done. This helps reduce complexity and increases code clarity. run-time.

Overloading increases code clarity, while overriding provides


7. Explain Inheritance and its types. specific behavior in child classes.

Inheritance means a class (child class) can reuse the properties and
methods of another class (parent class). It reduces redundancy.
10. Explain the difference between Compile-time Polymorphism and Run- A destructor is a special method that destroys or cleans up an
time Polymorphism. object when it is no longer needed.

 Compile-time Polymorphism: The method call is resolved at  In C++, it starts with ~ symbol and has no return type and no
compile time. Example: Method Overloading and Operator arguments. Example: ~Car() {}
Overloading.
 In Java, there are no destructors, but the Garbage
 Run-time Polymorphism: The method call is resolved during Collector automatically destroys unused objects.
program execution. Example: Method Overriding in inheritance.
Destructors are used to release memory or close connections when an
Compile-time is faster but less flexible, while run-time allows
object is destroyed.
dynamic method behavior based on the object type.

14. Difference between constructor and method.


11. What is a constructor?

A constructor is a special method used to create and initialize Feature Constructor Method
objects of a class. It has the same name as the class and does not
have a return type, not even void. Defines an object's
Example: Purpose Initializes an object behavior
class Car { public: Car() { cout << "Car created"; } };
Name Same as the class name Any valid name
When you create an object of Car, the constructor is called
automatically.
Its main purpose is to assign default values to the variables of the Return
object or run setup code when an object is created. type No return type Has a return type

Automatically during object Manually by calling the


12. Types of constructors in C++/Java. Called by creation method
There are mainly three types of constructors:
Example Car() drive()
 Default Constructor: Takes no arguments and sets default values.

 Parameterized Constructor: Takes arguments to assign values


during object creation.
15. What is a static method?
 Copy Constructor (C++): Creates a new object as a copy of an
existing object. A static method belongs to the class, not to the objects. It means we
Example in C++: don’t need to create an object to call it.
Example in Java:
Car() {...} // Default Car(string color) {...} // Parameterized
Car(const Car &obj) {...} // Copy public static void display() { System.out.println("Hello"); }

Called as: ClassName.display();


Static methods are mostly used for utility or helper functions that
13. What is a destructor?
do not depend on object data.
16. Can constructors be inherited?

No, constructors cannot be inherited. 20. What is the use of friend function in C++?
Each class defines its own constructors. But a child class can call
A friend function is a function that is not a member of a class but
the parent class’s constructor using the super() keyword in Java or
can access its private and protected data.
an initializer list in C++.
Syntax:
So, while inheritance applies to properties and methods, constructors
are not inherited but can be called. class Car { friend void display(Car obj); };

Used when external functions need access to class internals without


being a class member. This breaks encapsulation a little, so it
17. What is the purpose of the ‘this’ keyword?
should be used carefully.
The this keyword refers to the current object of the class.
It is mainly used when variable names overlap between method
parameters and instance variables. Example: 21. Types of inheritance with examples.
class Car { String color; Car(String color) { this.color = color; } } Inheritance types define how classes are connected:
Here, this.color refers to the class variable, and color refers to 1. Single Inheritance: One child inherits from one parent.
the method parameter. Example: Dog → Animal.

2. Multilevel Inheritance: A class inherits from a class that


already inherited from another.
18. What is the use of the ‘super’ keyword?
Example: Class C → Class B → Class A.
The super keyword refers to the parent class.
3. Hierarchical Inheritance: Multiple child classes inherit from a
It is used to:
single parent.
1. Call the parent class’s constructor: super(); Example: Dog, Cat, Bird → Animal.

2. Access the parent class’s variables and methods that are hidden 4. Multiple Inheritance (C++ supports it): One child inherits from
by child class. multiple parents.
Example in Java: Example: Class D inherits from Class A and Class B.

super.display(); 5. Hybrid Inheritance: Combination of two or more inheritance


types.
This helps in reusing the parent class features inside the child
class. In Java, multiple inheritance of classes is not allowed to avoid
confusion but supported in C++.

19. What is a copy constructor?


22. What is multiple inheritance? Does Java support it?
A copy constructor is a special constructor in C++ used to create a
new object by copying an existing object. Multiple inheritance means a child class inherits from two or more
Example: parent classes.
In C++, this is allowed. Example:
Car(const Car &obj) { this->color = obj.color; }
class Child : public Parent1, public Parent2 { };
It is useful when we want to duplicate objects with the same data.
But in Java, multiple inheritance of classes is not supported because 26. What happens if a class is derived from two classes having the
it may lead to confusion, called the diamond problem. same method?
Java solves this by allowing multiple interfaces instead.
In C++, if two parent classes have the same method name, the child
class needs to specify which class’s method to use, otherwise the
compiler gets confused.
23. What is hybrid inheritance?
Example:
Hybrid inheritance is a combination of two or more types of
a.Parent1::display();
inheritance.
Example: A program might use hierarchical and multiple inheritance This situation is called ambiguity, and it’s resolved by explicitly
together. mentioning the parent class name.

class A {...}; class B: public A {...}; class C {...}; class D:


public B, public C {...};
27. What is the Diamond problem in inheritance?
In languages like C++, hybrid inheritance needs virtual
The diamond problem happens when a class inherits from two classes,
inheritance to avoid ambiguity.
and both of them inherit from the same class.
Example:

24. Explain hierarchical inheritance. A

Hierarchical inheritance means one parent class is inherited by / \


multiple child classes.
B C
Example:
\ /
class Animal {...}; class Dog: public Animal {...}; class Cat: public
Animal {...}; D
Here, both Dog and Cat inherit properties like eat() from the Animal If D inherits from both B and C, and B and C both inherit from A,
class. then D has two copies of A’s methods and properties, causing
It’s useful when you have a common base class and several special confusion.
classes. C++ solves it using virtual inheritance.
Java avoids this problem by not allowing multiple inheritance of
classes.
25. How do you achieve multiple inheritance in Java?

In Java, multiple inheritance is achieved using interfaces, because


28. What is function overloading?
Java does not allow multiple inheritance with classes.
Example: Function overloading means having multiple functions with the same
name but different arguments.
interface A { void display(); } interface B { void show(); } class C
Example in C++:
implements A, B { public void display() {...} public void show()
{...} } void add(int a, int b); void add(float a, float b);
By implementing multiple interfaces, a class can get functionalities The compiler knows which function to call based on the parameters.
from multiple sources without confusion. It is an example of compile-time polymorphism, making code easier to
read and reuse.
32. What is dynamic binding and static binding?

29. What is operator overloading in C++?  Static Binding: The method call is decided at compile time.
Example: method overloading.
Operator overloading means giving special meaning to operators like
+, -, ==, etc., for user-defined objects.  Dynamic Binding: The method call is decided at runtime,
Example: depending on the object type. Example: method overriding.

class Complex { Complex operator + (Complex obj) {...} }; Example:

This allows adding two complex numbers using the + operator. Animal a = new Dog(); a.sound(); // Dynamic binding: decides at
It helps objects behave more like built-in types. runtime which sound() to call

Static binding is faster, but dynamic binding gives flexibility to


override methods in child classes.
30. Explain method overriding with an example.

Method overriding means redefining a method in a child class that is


already present in the parent class. 33. Explain late binding in OOPS.
Example in Java:
Late binding is another term for dynamic binding.
class Animal { void sound() { System.out.println("Animal sound"); } } It means the decision about which method to call is made at runtime,
class Dog extends Animal { void sound() { System.out.println("Bark"); not at compile time.
} } For example:

When you call sound() on a Dog object, it prints "Bark", not "Animal Animal animal = new Dog(); animal.sound();
sound."
At runtime, it binds the Dog's sound() method, not Animal's.
This is an example of runtime polymorphism, where the method behavior
Late binding is essential for polymorphism, especially in large
depends on the object type.
systems where object types may not be known until runtime.

31. Can static methods be overridden?


34. What is data hiding?
No, static methods cannot be overridden because they belong to
Data hiding means protecting the internal data of a class from direct
the class, not the object.
access by outside code.
If you declare a static method with the same name in a child class,
It is achieved using access modifiers like private and protected.
it hides the parent’s static method, but it’s not overriding. This is
Example:
called method hiding.
Example in Java: private int balance;
class Parent { static void display() { System.out.println("Parent"); Access is given through getter and setter methods, allowing control
} } over how data is accessed or modified. This protects the object from
unwanted changes and maintains security.
class Child extends Parent { static void display() {
System.out.println("Child"); } }

Here, calling Child.display() does not override but 35. What are access modifiers? List them.
hides Parent.display().
Access modifiers control where a class, variable, or method can be Abstraction is about what to hide, encapsulation is about how to
accessed from. protect data.
In Java, they are:

 public: Accessible from anywhere.


38. Why is encapsulation called data hiding?
 private: Accessible only within the same class.
Encapsulation is called data hiding because it hides the internal
 protected: Accessible in the same package and in child classes. state of an object and only exposes selected methods to access it.
Example: In a Bank class, the balance is private. You can't change it
 default (no keyword): Accessible only within the same package.
directly; you must use deposit() and withdraw().
These help implement encapsulation and data hiding. This protects the object from incorrect or unauthorized changes and
makes the program secure.

36. Difference between public, private, and protected access


modifiers. 39. Example of abstraction in real life.

Accessible A simple example is a coffee machine.


Accessible Within Accessible by Accessible You press a button to make coffee without knowing how it mixes water,
Modifier Within Class Package Subclasses Anywhere coffee powder, and heats it.
Similarly, in programming, when you call a method like sort(), you
don’t know how the sorting algorithm works internally; you only know
public Yes Yes Yes Yes
that it sorts the data.
This is abstraction – hiding the inner complexity and showing only
protected Yes Yes Yes No the useful part.

default Yes Yes No No


40. Difference between interface and abstract class.

private Yes No No No Feature Abstract Class Interface

Public is open to all, private is strictly for the class itself, and Can have both abstract & Only abstract methods (Java
protected allows inheritance. Methods non-abstract methods 7), default/static (Java 8+)

Constants only (public static


37. How does abstraction differ from encapsulation? Variables Can have variables final)
 Abstraction: Hides implementation details and shows only
essential information. Example: We use a mobile without knowing Supports single Supports multiple inheritance
its internal circuits. Inheritance inheritance (of interfaces)

 Encapsulation: Hides data and controls its access. Example: Bank


account balance is private and only accessible through Constructors Can have constructors Cannot have constructors
deposit/withdraw methods.
Feature Abstract Class Interface interface Animal { default void eat() { System.out.println("Animal
eats"); } }

Purpose Partial abstraction Full abstraction This lets developers add new methods to interfaces without forcing
every implementing class to override them.
When classes are closely When unrelated classes need
Usage related to share behavior
44. Can a class implement multiple interfaces?

Example: Use an abstract class when classes share common behavior, Yes, a class can implement multiple interfaces in Java. This is how
and use interfaces when different classes need to follow the same Java supports multiple inheritance of type.
contract. Example:

class Bird implements Flyable, Singable { ... }

41. Can we instantiate an abstract class? The class must implement all the methods declared in the interfaces.
This allows adding functionalities from many different sources.
No, we cannot create an object of an abstract class because an
abstract class is incomplete. It may contain abstract methods without
a body. 45. What happens if a class does not implement all methods of an
However, we can create a reference of an abstract class and assign it interface?
to a child class object.
Example in Java: If a class does not implement all the methods of an interface, then
that class must be declared as abstract.
AbstractAnimal animal = new Dog(); Example:
Abstract classes are meant to be extended by child classes where the abstract class Animal implements Walkable { // Walkable's method is
abstract methods are implemented. not implemented }

An abstract class is allowed to leave methods unimplemented, but a


42. Can an interface contain constructors? regular (non-abstract) class must implement everything.

No, interfaces cannot have constructors because they are not meant to
create objects. 46. What is an inner class?
Interfaces only declare method signatures, not implementations.
Constructors are used to initialize objects, and since you can’t An inner class is a class defined inside another class.
create an object of an interface, constructors are not allowed in it. It helps logically group classes that are only used by their outer
class.
Example:
43. What is the default method in an interface? class Outer { class Inner { void display() {
In Java 8 and later, a default method is a method in an interface System.out.println("Inner class"); } } }
that has a body (implementation). It helps in organizing code and increasing encapsulation.
It helps interfaces evolve without breaking the classes that
implement them.
Example: 47. Difference between nested class and inner class.
 A nested class is any class inside another class. No, you cannot inherit a final class.
The whole purpose of declaring a class as final is to prevent other
 If it's static → Static nested class.
classes from extending it.
 If it's non-static → Inner class. For example, in Java, the String class is final, so no one can modify
its behavior through inheritance.
Feature Static Nested Class Inner Class

Static/Non- 51. Can a class be both abstract and final?


static Static Non-static
No, a class cannot be both abstract and final.

Access to outer Cannot access non-static Can access outer class  An abstract class means it’s incomplete and must be extended to
class members members provide full implementation.

 A final class means it cannot be extended by any other class.


Object creation Outer.StaticNested Outer.Inner If a class is final, it can’t be extended, and if it’s abstract,
it must be extended, so combining both makes no sense.

48. What is an anonymous class? 52. Can we declare a class static?


An anonymous class is a class without a name, declared and In Java, only nested (inner) classes can be static, not top-level
instantiated at the same time. classes.
It's mostly used for quick implementation of interfaces or abstract Example:
classes.
Example: class Outer { static class StaticNested { } }

Runnable r = new Runnable() { public void run() { A static nested class does not require an object of the outer
System.out.println("Running"); } }; class to be created.
However, you cannot declare a top-level class static because it does
It simplifies coding when you need a short, one-time-use class. not belong to another class.

49. Explain the use of final keyword in class. 53. What is UML in OOPS?
When you declare a class as final, it cannot be inherited. UML (Unified Modeling Language) is a visual modeling language used to
Example: represent the structure and behavior of an object-oriented system.
final class Animal { ... } In OOPS, UML helps developers to:

This is useful when you want to prevent modification or extension of  Design class diagrams to show classes and relationships.
a class’s behavior, ensuring security and stability.  Visualize how objects interact.

 Plan inheritance and interfaces.


50. Can we inherit a final class?
UML diagrams like Class Diagram, Sequence Diagram, and Use Case Feature Aggregation Composition
Diagram help in planning and communicating designs clearly before
writing code.
Type of relationship Weak "has-a" Strong "has-a"

54. Explain the concept of Association. Child lifecycle Can exist without parent Dies with the parent

Association represents a relationship between two independent


classes where one class uses another. Example Library and Books House and Rooms
Example:
A Teacher and a Department – A teacher works in a department but both Dependency Low High
are independent entities.
Association can be one-to-one, one-to-many, or many-to-many.
It simply shows how objects communicate or relate without ownership.
58. What is dependency in OOPS?

55. Explain Aggregation with an example. Dependency is a relationship where one class depends on another to
perform its task.
Aggregation is a special type of Association where one class is Example: A Printer class depends on a Paper class. Without paper,
a part of another but can exist independently. printing doesn’t happen.
Example: It is the loosest relationship, meaning the dependent class uses the
A Library and Books – Even if the library closes, the books still other class temporarily during a method execution.
exist. Dependency is represented in UML using a dashed arrow.
In code:

class Library { List<Book> books; }


59. What is object cloning?
It represents a "has-a" relationship, but it is a weaker
relationship than composition. Object cloning means creating an exact copy of an object.
In Java, we use the clone() method, which creates a new object with
the same field values as the original.
Example:
56. Explain Composition with an example.

Composition is a stronger form of Aggregation. If the parent object Employee e2 = (Employee) e1.clone();
is destroyed, the child object is also destroyed. Cloning is useful when you want identical objects with separate
Example: memory locations.
A House and Rooms – If the house is destroyed, the rooms no longer
exist.
In code: 60. What is shallow copy and deep copy?
class House { private Room room = new Room(); } Type Explanation Example
It tightly binds the child object’s lifecycle to the parent object.
Shallow
Copies the object's fields, but if Cloning an object
Copy
57. Difference between aggregation and composition. there are references to other that contains another
Type Explanation Example 63. Difference between stack and heap memory for objects.

Aspect Stack Memory Heap Memory


objects, only the references are object by copying the
copied, not the actual objects. reference.
Stores method calls, Stores objects and instance
Purpose local variables variables
Copies the object along with all Creating a full copy
Deep the nested objects. Every of the object and its
Short-lived, removed when Long-lived, stays until
Copy referenced object is also cloned. contained objects.
Lifetime method ends garbage collected

Shallow copy is faster but may cause unexpected issues if nested Access
objects are modified. Deep copy is safer but takes more time and speed Faster Slower
memory.

Example int a = 10; Employee e = new Employee();


61. Explain Garbage Collection in Java.

Garbage Collection (GC) in Java is the process by which unused or In OOPS, objects are always created in the heap, while reference
unreachable objects are automatically removed from memory to free up variables can be on the stack.
space.
Java has a built-in garbage collector that runs in the background and
checks for objects that are no longer referenced by any part of the 64. Write a program to show inheritance in C++.
program. #include <iostream> using namespace std; class Animal { public: void
This makes Java a memory-managed language, preventing memory leaks. eat() { cout << "Eating..." << endl; } }; class Dog : public Animal {
Example: If an object is no longer used in your code, the garbage public: void bark() { cout << "Barking..." << endl; } }; int main() {
collector removes it from the heap memory automatically. Dog d; d.eat(); // Inherited from Animal d.bark(); // Own method
return 0; }

62. How does the finalize() method work?

The finalize() method is a protected method of the Object class that 65. Write a program for method overriding.
Java calls before garbage collecting an object. Example in Java:
You can override finalize() to perform cleanup tasks like closing
files or releasing resources. class Animal { void sound() { System.out.println("Animal makes
Example: sound"); } } class Dog extends Animal { void sound() {
System.out.println("Dog barks"); } } public class Main { public
protected void finalize() throws Throwable { static void main(String[] args) { Animal a = new Dog(); a.sound(); //
System.out.println("Object is being destroyed"); } Output: Dog barks } }
Note: As of Java 9+, the use of finalize() is discouraged because
it can cause performance problems. Instead, use try-with-resources or
explicit cleanup. 66. Create a program using abstract class and interface.

interface Flyable { void fly(); } abstract class Bird { abstract void


eat(); } class Sparrow extends Bird implements Flyable { void eat() {
System.out.println("Sparrow eats grains"); } public void fly() { 70. What is the role of OOPS in game development?
System.out.println("Sparrow flies"); } } public class Test { public
In game development, OOPS helps developers to create games that
static void main(String[] args) { Sparrow s = new Sparrow(); s.eat();
are modular, reusable, and easy to extend.
s.fly(); } }
 Characters, enemies, weapons, and levels are all modeled
as objects.
67. Write a class to implement encapsulation.
 Inheritance helps create different character types (e.g.,
class Student { private int age; public void setAge(int a) { if (a > player, enemy) with shared features.
0) age = a; } public int getAge() { return age; } } public class Test
 Polymorphism lets you treat different enemies similarly when
{ public static void main(String[] args) { Student s = new Student();
updating their positions.
s.setAge(20); System.out.println(s.getAge()); } }
 Encapsulation keeps the character data (like health) safe.
Here, age is private, accessed only through getAge() and setAge() →
Encapsulation. Using OOPS, games can be built with clear structure, supporting large
and complex systems like Unity or Unreal Engine.

68. Write a program to demonstrate polymorphism.


71. What is method hiding in OOPS?
class Shape { void draw() { System.out.println("Drawing shape"); } }
class Circle extends Shape { void draw() { Method hiding occurs when a child class defines a static method with
System.out.println("Drawing circle"); } } class Square extends Shape the same name as a static method in the parent class.
{ void draw() { System.out.println("Drawing square"); } } public In this case, the child’s method hides the parent’s version, but it
class Main { public static void main(String[] args) { Shape s1 = new does not override it.
Circle(); Shape s2 = new Square(); s1.draw(); // Circle s2.draw(); // Example:
Square } }
class Parent { static void display() { System.out.println("Parent");
} } class Child extends Parent { static void display() {
System.out.println("Child"); } }
69. How is OOPS used in software design?
When called using the class name, the method from that class is used.
OOPS is the foundation of modern software design because it allows
developers to model real-world entities in software.

 Classes represent business models like Customer, Account, or 72. Difference between method hiding and overriding.
Order.
Feature Method Overriding Method Hiding
 Inheritance allows reusing code efficiently.

 Polymorphism lets objects behave differently based on their Method type Instance methods Static methods
types.

 Encapsulation protects sensitive data. Binding time Runtime Compile-time

OOPS enables modular, scalable, and maintainable software


development, making it easy to update or extend parts of the system Purpose Polymorphism Hiding, no polymorphism
without affecting the whole application.
Feature Method Overriding Method Hiding
76. What are the benefits of constructor overloading?
Object/Class Calls depend on object Calls depend on class
 Allows creating objects with different sets of initial data.
call type reference
 Improves flexibility and code readability.

 Reduces the need to create multiple classes for different


initialization cases.
73. Can a constructor be static?
Example:
No, a constructor cannot be static because it is used to initialize You can create a Car with just color or both color and speed
instances of a class, and static belongs to the class itself, not using different constructors.
instances.
Static is used for class-level features, while constructors work at
the object level. 77. What is the difference between class and structure in C++?

Feature Class Structure


74. Can we overload constructors?
Default access Private Public
Yes, we can overload constructors. Constructor overloading
means creating multiple constructors in the same class with different
argument lists. OOPS support Supports all OOPS features Limited OOPS support
Example:

class Car { Car() { } Car(String color) { } Car(String color, int Usage Complex data and functions Simple data grouping
speed) { } }

It provides flexibility in creating objects in different ways. In modern C++, structures can also have functions, but traditionally,
they were used only to store data.

75. What is the difference between overloaded constructors and


overloaded methods? 78. Can we have functions inside a structure in C++?

Feature Overloaded Constructors Overloaded Methods Yes, in modern C++, you can define member functions inside a
structure, just like in a class.
Example:
Initialize objects in Perform different tasks using
Purpose different ways same method name struct Point { int x, y; void display() { cout << x << "," << y; } };

This is helpful for small utility structures.


Return
type No return type Must have a return type
79. What is the meaning of 'is-a' and 'has-a' relationship in OOPS?
Called  is-a: Represents inheritance. Example: A Dog is-a Animal.
when Object is created Object calls the method
 has-a: Represents association or composition. Example: A
Car has-a Engine.
‘is-a’ makes the child class inherit the parent’s features, 82. What is upcasting and downcasting in OOPS?
while ‘has-a’ means one object is used within another.
 Upcasting: Converting a child class object to a parent class
type. Safe and automatic.
Example: Animal a = new Dog();
80. What is the difference between association, aggregation, and
composition?  Downcasting: Converting a parent class reference back to a child
class. Requires explicit casting and may cause errors if not
Relationship Example Ownership Lifecycle dependency handled properly.
Example: Dog d = (Dog) a;
Teacher and
Upcasting is common in polymorphism; downcasting is used when we need
Association Department No Independent
child-specific behavior.

Books survive without


Aggregation Library and Books Weak "has-a" library 83. What is type casting in OOPS?

Type casting is converting one data type or object type into another.
Strong "has- In OOPS, it mainly refers to converting parent class references to
Composition House and Rooms a" Rooms die with house child class references (downcasting) or vice versa (upcasting).
It helps in writing flexible and reusable code but should be done
Association is general linking, aggregation is weak ownership, and carefully to avoid errors.
composition is strong ownership.

84. Explain the difference between abstract class and interface in


81. Explain the difference between early binding and late binding. C++.

C++ has abstract classes, but not interfaces like Java.


Early Binding (Static
Feature Binding) Late Binding (Dynamic Binding)  Abstract class: Has both abstract (pure virtual) and concrete
methods.
Decided at Compile-time Runtime  Interface in C++: Simulated using a class with only pure virtual
functions and no data members.
Example Method overloading Method overriding Example:

class Interface { public: virtual void show() = 0; // pure virtual


Speed Faster Slower function };

Highly flexible (supports


Flexibility Less flexible polymorphism) 85. Can a destructor be virtual in C++? Why?

Yes, destructors in C++ should be virtual in base classes when using


inheritance.
In early binding, the compiler knows which method to call. In late
If the destructor is not virtual, deleting a derived class object
binding, the decision is made at runtime based on the actual object.
through a base class pointer may not call the derived class’s
destructor, leading to memory leaks. Feature Virtual Function Pure Virtual Function
Example:

class Base { virtual ~Base() {} }; Definition Has a body No body (= 0)

Override Can be overridden Must be overridden


86. What is multiple level inheritance in C++?

Multilevel inheritance means a class inherits from a class, which Class type Concrete or abstract Abstract
itself inherits from another class.
Example:

class A { }; class B : public A { }; class C : public B { };


90. Explain function templates in C++.
This forms a chain of inheritance, allowing features to pass through
multiple levels. A function template is a way to create a single function to work with
different data types.
Instead of writing multiple functions for int, float, and double, you
87. What is the virtual function in C++? write one template.
Example:
A virtual function is a function in a base class that you
can override in derived classes. template <typename T> T add(T a, T b) { return a + b; }
When called through a base class pointer, the derived class’s version Function templates help in writing generic and reusable code.
is used if overridden.
Example:

class Base { public: virtual void show() { cout << "Base"; } }; 91. What are class templates in C++?

Used for runtime polymorphism. Class templates allow you to create a single class that works with
any data type.
Example:
88. What is pure virtual function in C++? template <class T> class Box { T data; };
A pure virtual function has no body in the base class and must Instead of creating separate classes for int, float, etc., you use
be overridden by derived classes. templates.
It is written like this: They promote code reusability and type safety.
virtual void show() = 0;

If a class contains a pure virtual function, the class 92. Difference between function templates and class templates.
becomes abstract and cannot be instantiated.
Feature Function Template Class Template

89. What is the difference between virtual function and pure virtual Purpose Works for functions Works for classes
function?

Feature Virtual Function Pure Virtual Function Syntax template <typename T> template <typename T>
Feature Function Template Class Template class Singleton { private static Singleton instance = new
Singleton(); private Singleton() { } public static Singleton
getInstance() { return instance; } }
Example add<int>(a, b) Box<int> myBox;

Both support generic programming, but one is for functions, the other 96. What is an immutable class?
for entire classes.
An immutable class means its objects cannot be changed once created.
Example: Java's String class is immutable.
Key features:
93. Explain friend class in C++.
 Class marked final
A friend class is allowed to access private and protected members of
another class.  Private fields
Example:
 No setter methods
class B; class A { friend class B; };
 Values set through the constructor
Used when two classes are closely related and need to share internal
data.
It breaks strict encapsulation, so use carefully. 97. Difference between mutable and immutable objects.

Feature Mutable Immutable


94. Can a constructor be private in C++/Java?
Changeable Can be modified Cannot be modified
Yes, a constructor can be private.

 In C++/Java, private constructors are used to control object Example ArrayList, StringBuilder String, Integer
creation, such as in Singleton design patterns.
Example in Java:
Use case Frequent modifications Security, thread safety
private MyClass() { }

The class then controls when and how objects are created.

98. Explain the 'instanceof' keyword in Java.


95. Explain the Singleton class. The instanceof keyword checks whether an object belongs to a specific
A Singleton class ensures that only one object of the class exists at class or subclass.
a time. Example:
Key features: if (obj instanceof Dog) { System.out.println("It is a Dog"); }
 Private constructor It’s useful when working with polymorphism to safely downcast
 Static object reference objects.

 Public method to access the single object


Example: 99. Explain encapsulation with a real-world example.
A real-world example of encapsulation is a bank account.

 The balance is private, and you can only access it through


deposit() and withdraw() methods.
This protects the balance from direct changes and keeps the
data safe and controlled.

100. How do OOPS concepts improve code maintainability?

OOPS concepts like encapsulation, inheritance, and polymorphism help


organize code into logical, reusable, and independent modules.

 Changes in one class don’t affect other classes.

 You can extend functionality without modifying existing code.

 Objects model real-world entities, making code easier to


understand and maintain.

You might also like