0% found this document useful (0 votes)
48 views85 pages

OOPs Features and Programming Models

Uploaded by

hy148964
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)
48 views85 pages

OOPs Features and Programming Models

Uploaded by

hy148964
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/ 85

Basic OOPs Interview Questions

1. What is the need for OOPs?

There are many reasons why OOPs is mostly preferred, but the most important among them are:

 OOPs helps users to understand the software easily, although they don’t know the actual
implementation.
 With OOPs, the readability, understandability, and maintainability of the code increase multifold.
 Even very big software can be easily written and managed easily using OOPs.

2. What are some major Object Oriented Programming languages?

The programming languages that use and follow the Object-Oriented Programming paradigm or
OOPs, are known as Object-Oriented Programming languages. Some of the major Object-Oriented
Programming languages include:

 Java
 C++
 Javascript
 Python
 PHP

And many more.

3. What are some other programming paradigms other than OOPs?

Programming paradigms refers to the method of classification of programming languages based on


their features. There are mainly two types of Programming Paradigms:

 Imperative Programming Paradigm


 Declarative Programming Paradigm

Now, these paradigms can be further classified based:

1. Imperative Programming Paradigm: Imperative programming focuses on HOW to execute


program logic and defines control flow as statements that change a program state. This can be
further classified as:
a) Procedural Programming Paradigm: Procedural programming specifies the steps a program must
take to reach the desired state, usually read in order from top to bottom.
b) Object-Oriented Programming or OOP: Object-oriented programming (OOP) organizes programs
as objects, that contain some data and have some behavior.
c) Parallel Programming: Parallel programming paradigm breaks a task into subtasks and focuses
on executing them simultaneously at the same time.

2. Declarative Programming Paradigm: Declarative programming focuses on WHAT to execute


and defines program logic, but not a detailed control flow. Declarative paradigm can be further
classified into:
a) Logical Programming Paradigm: Logical programming paradigm is based on formal logic, which
refers to a set of sentences expressing facts and rules about how to solve a problem
b) Functional Programming Paradigm: Functional programming is a programming paradigm where
programs are constructed by applying and composing functions.
c) Database Programming Paradigm: Database programming model is used to manage data and
information structured as fields, records, and files.

4. What is meant by Structured Programming?

Structured Programming refers to the method of programming which consists of a completely


structured control flow. Here structure refers to a block, which contains a set of rules, and has a
definitive control flow, such as (if/then/else), (while and for), block structures, and subroutines.

Nearly all programming paradigms include Structured programming, including the OOPs model.

5. What are the main features of OOPs?

OOPs or Object Oriented Programming mainly comprises of the below four features, and make sure
you don't miss any of these:

 Inheritance
 Encapsulation
 Polymorphism
 Data Abstraction

6. What are some advantages of using OOPs?

 OOPs is very helpful in solving very complex level of problems.


 Highly complex programs can be created, handled, and maintained easily using object-oriented
programming.
 OOPs, promote code reuse, thereby reducing redundancy.
 OOPs also helps to hide the unnecessary details with the help of Data Abstraction.
 OOPs, are based on a bottom-up approach, unlike the Structural programming paradigm, which
uses a top-down approach.
 Polymorphism offers a lot of flexibility in OOPs.

7. Why is OOPs so popular?


OOPs programming paradigm is considered as a better style of programming. Not only it helps in
writing a complex piece of code easily, but it also allows users to handle and maintain them easily
as well. Not only that, the main pillar of OOPs - Data Abstraction, Encapsulation, Inheritance, and
Polymorphism, makes it easy for programmers to solve complex scenarios. As a result of these,
OOPs is so popular.

8. What is meant by the term OOPs?

OOPs refers to Object-Oriented Programming. It is the programming paradigm that is defined using
objects. Objects can be considered as real-world instances of entities like class, that have some
characteristics and behaviors.

Advanced OOPs Interview Questions


1. What are access specifiers and what is their significance?

Access specifiers, as the name suggests, are a special type of keywords, which are used to control or specify
the accessibility of entities like classes, methods, etc. Some of the access specifiers or access modifiers
include “private”, “public”, etc. These access specifiers also play a very vital role in achieving Encapsulation
- one of the major features of OOPs.

2. Are there any limitations of Inheritance?

Yes, with more powers comes more complications. Inheritance is a very powerful feature in OOPs, but it has
some limitations too. Inheritance needs more time to process, as it needs to navigate through multiple classes
for its implementation. Also, the classes involved in Inheritance - the base class and the child class, are very
tightly coupled together. So if one needs to make some changes, they might need to do nested changes in both
classes. Inheritance might be complex for implementation, as well. So if not correctly implemented, this
might lead to unexpected errors or incorrect outputs.

3. What are the various types of inheritance?

The various types of inheritance include:

 Single inheritance
 Multiple inheritances
 Multi-level inheritance
 Hierarchical inheritance
 Hybrid inheritance

4. What is a subclass?

The subclass is a part of Inheritance. The subclass is an entity, which inherits from another class. It is also
known as the child class.

5. Define a superclass?
Superclass is also a part of Inheritance. The superclass is an entity, which allows subclasses or child classes to
inherit from itself.

6. What is an interface?

An interface refers to a special type of class, which contains methods, but not their definition. Only the
declaration of methods is allowed inside an interface. To use an interface, you cannot create objects. Instead,
you need to implement that interface and define the methods for their implementation.

7. What is meant by static polymorphism?

Static Polymorphism is commonly known as the Compile time polymorphism. Static polymorphism is the
feature by which an object is linked with the respective function or operator based on the values during the
compile time. Static or Compile time Polymorphism can be achieved through Method overloading or operator
overloading.

8. What is meant by dynamic polymorphism?

Dynamic Polymorphism or Runtime polymorphism refers to the type of Polymorphism in OOPs, by which
the actual implementation of the function is decided during the runtime or execution. The dynamic or runtime
polymorphism can be achieved with the help of method overriding.

9. What is the difference between overloading and overriding?

Overloading is a compile-time polymorphism feature in which an entity has multiple implementations with
the same name. For example, Method overloading and Operator overloading.

Whereas Overriding is a runtime polymorphism feature in which an entity has the same name, but its
implementation changes during execution. For example, Method overriding.
Image

10. How is data abstraction accomplished?

Data abstraction is accomplished with the help of abstract methods or abstract classes.

11. What is an abstract class?


An abstract class is a special class containing abstract methods. The significance of abstract class is that the
abstract methods inside it are not implemented and only declared. So as a result, when a subclass inherits the
abstract class and needs to use its abstract methods, they need to define and implement them.

12. How is an abstract class different from an interface?

Interface and abstract classes both are special types of classes that contain only the methods declaration and
not their implementation. But the interface is entirely different from an abstract class. The main difference
between the two is that when an interface is implemented, the subclass must define all its methods and
provide its implementation. Whereas in object-oriented programming, when a subclass inherits from an
abstract class with abstract methods, the subclass is generally required to provide concrete implementations
for all of those abstract methods in the abstract class unless the subclass itself is declared as abstract.

Also, an abstract class can contain abstract methods as well as non-abstract methods.

13. Explain Inheritance with an example?

Inheritance is one of the major features of object-oriented programming, by which an entity inherits some
characteristics and behaviors of some other entity and makes them their own. Inheritance helps to improve
and facilitate code reuse.

Let me explain to you with a common example. Let's take three different vehicles - a car, truck, or bus. These
three are entirely different from one another with their own specific characteristics and behavior. But. in all
three, you will find some common elements, like steering wheel, accelerator, clutch, brakes, etc. Though
these elements are used in different vehicles, still they have their own features which are common among all
vehicles. This is achieved with inheritance. The car, the truck, and the bus have all inherited the features like
steering wheel, accelerator, clutch, brakes, etc, and used them as their own. Due to this, they did not have to
create these components from scratch, thereby facilitating code reuse.

14. What is an exception?

An exception can be considered as a special event, which is raised during the execution of a program at
runtime, that brings the execution to a halt. The reason for the exception is mainly due to a position in the
program, where the user wants to do something for which the program is not specified, like undesirable input.

15. What is meant by exception handling?


No one wants its software to fail or crash. Exceptions are the major reason for software failure. The
exceptions can be handled in the program beforehand and prevent the execution from stopping. This is known
as exception handling.
So exception handling is the mechanism for identifying the undesirable states that the program can reach and
specifying the desirable outcomes of such states.
Try-catch is the most common method used for handling exceptions in the program.

16. What is meant by Garbage Collection in OOPs world?

Object-oriented programming revolves around entities like objects. Each object consumes memory and there
can be multiple objects of a class. So if these objects and their memories are not handled properly, then it
might lead to certain memory-related errors and the system might fail.

Garbage collection refers to this mechanism of handling the memory in the program. Through garbage
collection, the unwanted memory is freed up by removing the objects that are no longer needed.

17. Can we run a Java application without implementing the OOPs concept?

No. Java applications are based on Object-oriented programming models or OOPs concept, and hence they
cannot be implemented without it.

However, on the other hand, C++ can be implemented without OOPs, as it also supports the C-like structural
programming model.

18. What is Compile time Polymorphism and how is it different from Runtime
Polymorphism?

Compile Time Polymorphism: Compile time polymorphism, also known as Static Polymorphism, refers to the
type of Polymorphism that happens at compile time. What it means is that the compiler decides what shape or
value has to be taken by the entity in the picture.

Example:

// In this program, we will see how multiple functions are created with the same name,
// but the compiler decides which function to call easily at the compile time itself.
class CompileTimePolymorphism{
// 1st method with name add
public int add(int x, int y){
return x+y;
}
// 2nd method with name add
public int add(int x, int y, int z){
return x+y+z;
}
// 3rd method with name add
public int add(double x, int y){
return (int)x+y;
}
// 4th method with name add
public int add(int x, double y){
return x+(int)y;
}
}
class Test{
public static void main(String[] args){
CompileTimePolymorphism demo=new CompileTimePolymorphism();
// In the below statement, the Compiler looks at the argument types and decides to
call method 1
System.out.println(demo.add(2,3));
// Similarly, in the below statement, the compiler calls method 2
System.out.println(demo.add(2,3,4));
// Similarly, in the below statement, the compiler calls method 4
System.out.println(demo.add(2,3.4));
// Similarly, in the below statement, the compiler calls method 3
System.out.println(demo.add(2.5,3));
}
}

In the above example, there are four versions of add methods. The first method takes two parameters while
the second one takes three. For the third and fourth methods, there is a change of order of parameters. The
compiler looks at the method signature and decides which method to invoke for a particular method call at
compile time.

Runtime Polymorphism: Runtime polymorphism, also known as Dynamic Polymorphism, refers to the type
of Polymorphism that happens at the run time. What it means is it can't be decided by the compiler. Therefore
what shape or value has to be taken depends upon the execution. Hence the name Runtime Polymorphism.

Example:

class AnyVehicle{
public void move(){
System.out.println(“Any vehicle should move!!”);
}
}
class Bike extends AnyVehicle{
public void move(){
System.out.println(“Bike can move too!!”);
}
}
class Test{
public static void main(String[] args){
AnyVehicle vehicle = new Bike();
// In the above statement, as you can see, the object vehicle is of type AnyVehicle
// But the output of the below statement will be “Bike can move too!!”,
// because the actual implementation of object ‘vehicle’ is decided during runtime
vehicle.move();
vehicle = new AnyVehicle();
// Now, the output of the below statement will be “Any vehicle should move!!”,
vehicle.move();
}
}
As the method to call is determined at runtime, as shown in the above code, this is called runtime
polymorphism.

19. What is a class?

A class can be understood as a template or a blueprint, which contains some values, known as member data or
member, and some set of rules, known as behaviors or functions. So when an object is created, it
automatically takes the data and functions that are defined in the class.
Therefore the class is basically a template or blueprint for objects. Also one can create as many objects as
they want based on a class.

For example, first, a car’s template is created. Then multiple units of car are created based on that template.

20. What is an object?

An object refers to the instance of the class, which contains the instance of the members and behaviors
defined in the class template. In the real world, an object is an actual entity to which a user interacts, whereas
class is just the blueprint for that object. So the objects consume space and have some characteristic behavior.
For example, a specific car.

21. What is encapsulation?

One can visualize Encapsulation as the method of putting everything that is required to do the job, inside a
capsule and presenting that capsule to the user. What it means is that by Encapsulation, all the necessary data
and methods are bind together and all the unnecessary details are hidden to the normal user. So Encapsulation
is the process of binding data members and methods of a program together to do a specific job, without
revealing unnecessary details.

Encapsulation can also be defined in two different ways:

1) Data hiding: Encapsulation is the process of hiding unwanted information, such as restricting access to
any member of an object.

2) Data binding: Encapsulation is the process of binding the data members and the methods together as a
whole, as a class.

22. What is Polymorphism?

Polymorphism is composed of two words - “poly” which means “many”, and “morph” which means
“shapes”. Therefore Polymorphism refers to something that has many shapes.

In OOPs, Polymorphism refers to the process by which some code, data, method, or object behaves
differently under different circumstances or contexts. Compile-time polymorphism and Run time
polymorphism are the two types of polymorphisms in OOPs languages.

23. How does C++ support Polymorphism?


C++ is an Object-oriented programming language and it supports Polymorphism as well:

 Compile Time Polymorphism: C++ supports compile-time polymorphism with the help of features like
templates, function overloading, and default arguments.
 Runtime Polymorphism: C++ supports Runtime polymorphism with the help of features like virtual functions.
Virtual functions take the shape of the functions based on the type of object in reference and are resolved at
runtime.

24. What is meant by Inheritance?

The term “inheritance” means “receiving some quality or behavior from a parent to an offspring.” In object -
oriented programming, inheritance is the mechanism by which an object or class (referred to as a child) is
created using the definition of another object or class (referred to as a parent). Inheritance not only helps to
keep the implementation simpler but also helps to facilitate code reuse.

25. What is Abstraction?

If you are a user, and you have a problem statement, you don't want to know how the components of the
software work, or how it's made. You only want to know how the software solves your problem. Abstraction
is the method of hiding unnecessary details from the necessary ones. It is one of the main features of OOPs.
For example, consider a car. You only need to know how to run a car, and not how the wires are connected
inside it. This is obtained using Abstraction.

26. How much memory does a class occupy?

Classes do not consume any memory. They are just a blueprint based on which objects are created. Now
when objects are created, they actually initialize the class members and methods and therefore consume
memory.

27. Is it always necessary to create objects from class?

No. An object is necessary to be created if the base class has non-static methods. But if the class has static
methods, then objects don’t need to be created. You can call the class method directly in this case , using the
class name.

28. What is a constructor?

Constructors are special methods whose name is the same as the class name. The constructors serve the
special purpose of initializing the objects.
For example, suppose there is a class with the name “MyClass”, then when you instantiate this class, you pass
the syntax:
MyClass myClassObject = new MyClass();

Now here, the method called after “new” keyword - MyClass(), is the constructor of this class. This will help
to instantiate the member data and methods and assign them to the object myClassObject.

29. What are the various types of constructors in C++?

The most common classification of constructors includes:


Default constructor: The default constructor is the constructor which doesn’t take any argument. It has no
parameters.

class ABC
{
int x;

ABC()
{
x = 0;
}
}

Parameterized constructor: The constructors that take some arguments are known as parameterized
constructors.

class ABC
{
int x;

ABC(int y)
{
x = y;
}
}

Copy constructor: A copy constructor is a member function that initializes an object using another object of
the same class.

class ABC
{
int x;

ABC(int y)
{
x = y;
}
// Copy constructor
ABC(ABC abc)
{
x = abc.x;
}
}

30. What is a copy constructor?

Copy Constructor is a type of constructor, whose purpose is to copy an object to another. What it means is
that a copy constructor will clone an object and its values, into another object, is provided that both the
objects are of the same class.

31. What is a destructor?

Contrary to constructors, which initialize objects and specify space for them, Destructors are also special
methods. But destructors free up the resources and memory occupied by an object. Destructors are
automatically called when an object is being destroyed.
32. Are class and structure the same? If not, what's the difference between a class and a
structure?

No, class and structure are not the same. Though they appear to be similar, they have differences that make
them apart. For example, the structure is saved in the stack memory, whereas the class is saved in the heap
memory. Also, Data Abstraction cannot be achieved with the help of structure, but with class, Abstraction is
majorly used.

OOPs Coding Problems


1. What is the output of the below code?
#include<iostream>

using namespace std;


class BaseClass1 {
public:
BaseClass1()
{ cout << " BaseClass1 constructor called" << endl; }
};

class BaseClass2 {
public:
BaseClass2()
{ cout << "BaseClass2 constructor called" << endl; }
};

class DerivedClass: public BaseClass1, public BaseClass2 {


public:
DerivedClass()
{ cout << "DerivedClass constructor called" << endl; }
};

int main()
{
DerivedClass derived_class;
return 0;
}

Output:

BaseClass1 constructor called


BaseClass2 constructor called
DerivedClass constructor called

Reason:
The above program demonstrates Multiple inheritances. So when the Derived class’s constructor is called, it
automatically calls the Base class's constructors from left to right order of inheritance.

2. What will be the output of the below code?


class Scaler
{
static int i;

static
{
System.out.println(“a”);

i = 100;
}
}

public class StaticBlock


{
static
{
System.out.println(“b”);
}

public static void main(String[] args)


{
System.out.println(“c”);

System.out.println(Scaler.i);
}
}

Output:

b
c
a
100

Reason:
Firstly the static block inside the main-method calling class will be implemented. Hence ‘b’ will be printed
first. Then the main method is called, and now the sequence is kept as expected.

3. Predict the output?


#include<iostream>
using namespace std;

class ClassA {
public:
ClassA(int ii = 0) : i(ii) {}
void show() { cout << "i = " << i << endl;}
private:
int i;
};

class ClassB {
public:
ClassB(int xx) : x(xx) {}
operator ClassA() const { return ClassA(x); }
private:
int x;
};

void g(ClassA a)
{ a.show(); }

int main() {
ClassB b(10);
g(b);
g(20);
getchar();
return 0;
}

Output:

i = 10
i = 20

Reason:
ClassA contains a conversion constructor. Due to this, the objects of ClassA can have integer values. So the
statement g(20) works. Also, ClassB has a conversion operator overloaded. So the statement g(b) also works.

4. What will be the output in below code?


public class Demo{
public static void main(String[] arr){
System.out.println(“Main1”);
}
public static void main(String arr){
System.out.println(“Main2”);
}
}

Output:

Main1

Reason:
Here the main() method is overloaded. But JVM only understands the main method which has a String[]
argument in its definition. Hence Main1 is printed and the overloaded main method is ignored.

5. Predict the output?


#include<iostream>
using namespace std;

class BaseClass{
int arr[10];
};

class DerivedBaseClass1: public BaseClass { };

class DerivedBaseClass2: public BaseClass { };

class DerivedClass: public DerivedBaseClass1, public DerivedBaseClass2{};

int main(void)
{
cout<<sizeof(DerivedClass);
return 0;
}

Output:

If the size of the integer is 4 bytes, then the output will be 80.
Reason:
Since DerivedBaseClass1 and DerivedBaseClass2 both inherit from class BaseClass, DerivedClass contains
two copies of BaseClass. Hence it results in wastage of space and a large size output. It can be reduced with
the help of a virtual base class.

6. What is the output of the below program?


#include<iostream>

using namespace std;


class A {
public:
void print()
{ cout <<" Inside A::"; }
};

class B : public A {
public:
void print()
{ cout <<" Inside B"; }
};

class C: public B {
};

int main(void)
{
C c;

c.print();
return 0;
}

Output:

Inside B

Reason:
The above program implements a Multi-level hierarchy. So the program is linearly searched up until a
matching function is found. Here, it is present in both classes A and B. So class B’s print() method is called


1. What is Object Oriented Programming (OOPs)?
Object Oriented Programming (also known as OOPs) is a programming paradigm where the
complete software operates as a bunch of objects talking to each other. An object is a collection of
data and the methods which operate on that data.
2. Why OOPs?
The main advantage of OOP is better manageable code that covers the following:
1. The overall understanding of the software is increased as the distance between the language
spoken by developers and that spoken by users.
2. Object orientation eases maintenance by the use of encapsulation. One can easily change the
underlying representation by keeping the methods the same.
3. The OOPs paradigm is mainly useful for relatively big software.
3. What is a Class?
A class is a building block of Object Oriented Programs. It is a user-defined data type that contains
the data members and member functions that operate on the data members. It is like a blueprint or
template of objects having common properties and methods.
4. What is an Object?
An object is an instance of a class. Data members and methods of a class cannot be used directly.
We need to create an object (or instance) of the class to use them. In simple terms, they are the actual
world entities that have a state and behavior.
C++JavaPythonC#
#include <iostream>
using namespace std;

// defining class
class Student {
public:
string name;
};

int main()
{

// creating object
Student student1;
// assigning member some value
student1.name = "Rahul";

cout << "student1.name: " << student1.name;

return 0;
}

Output
student1.name: Rahul
5. What are the main features of OOPs?
The main feature of the OOPs, also known as 4 pillars or basic principles of OOPs are as follows:
1. Encapsulation
2. Data Abstraction
3. Polymorphism
4. Inheritance
OOPs Main Features

6. What is Encapsulation?
Encapsulation is the binding of data and methods that manipulate them into a single unit such that
the sensitive data is hidden from the users
It is implemented as the processes mentioned below:
1. Data hiding: A language feature to restrict access to members of an object. For example,
private and protected members in C++.
2. Bundling of data and methods together: Data and methods that operate on that data are
bundled together. For example, the data members and member methods that operate on them are
wrapped into a single unit known as a class.

7. What is Abstraction?
Abstraction is similar to data encapsulation and is very important in OOP. It means showing only the
necessary information and hiding the other irrelevant information from the user. Abstraction is
implemented using classes and interfaces.
8. What is Polymorphism?
The word “Polymorphism” means having many forms. It is the property of some code to behave
differently for different contexts. For example, in C++ language, we can define multiple functions
having the same name but different working depending on the context.
Polymorphism can be classified into two types based on the time when the call to the object or
function is resolved. They are as follows:
 Compile Time Polymorphism
 Runtime Polymorphism
A) Compile-Time Polymorphism
Compile time polymorphism, also known as static polymorphism or early binding is the type of
polymorphism where the binding of the call to its code is done at the compile time. Method
overloading or operator overloading are examples of compile-time polymorphism.
B) Runtime Polymorphism
Also known as dynamic polymorphism or late binding, runtime polymorphism is the type of
polymorphism where the actual implementation of the function is determined during the runtime or
execution. Method overriding is an example of this method.
9. What is Inheritance? What is its purpose?
The idea of inheritance is simple, a class is derived from another class and uses data and
implementation of that other class. The class which is derived is called child or derived or subclass
and the class from which the child class is derived is called parent or base or superclass.
The main purpose of Inheritance is to increase code reusability. It is also used to achieve Runtime
Polymorphism.
10. What are access specifiers? What is their significance in OOPs?
Access specifiers are special types of keywords that are used to specify or control the accessibility of
entities like classes, methods, and so on. Private, Public, and Protected are examples of access
specifiers or access modifiers.
The key components of OOPs, encapsulation and data hiding, are largely achieved because of these
access specifiers.
11. What are the advantages and disadvantages of OOPs?
Advantages of OOPs Disadvantages of OOPs

The programmer should be well-skilled and should have


OOPs provides enhanced code reusability. excellent thinking in terms of objects as everything is
treated as an object in OOPs.

The code is easier to maintain and Proper planning is required because OOPs is a little bit
update. tricky.

It provides better data security by


restricting data access and avoiding OOPs concept is not suitable for all kinds of problems.
unnecessary exposure.
Advantages of OOPs Disadvantages of OOPs

Fast to implement and easy to redesign


The length of the programs is much larger in comparison
resulting in minimizing the complexity of
to the procedural approach.
an overall program.

12. What other paradigms of programming exist besides OOPs?


The programming paradigm is referred to the technique or approach of writing a program. The
programming paradigms can be classified into the following types:

1. Imperative Programming Paradigm


It is a programming paradigm that works by changing the program state through assignment
statements. The main focus in this paradigm is on how to achieve the goal. The following
programming paradigms come under this category:
1. Procedural Programming Paradigm: This programming paradigm is based on the procedure
call concept. Procedures, also known as routines or functions are the basic building blocks of a
program in this paradigm.
2. Object-Oriented Programming or OOP: In this paradigm, we visualize every entity as an
object and try to structure the program based on the state and behavior of that object.
3. Parallel Programming: The parallel programming paradigm is the processing of instructions
by dividing them into multiple smaller parts and executing them concurrently.
2. Declarative Programming Paradigm
Declarative programming focuses on what is to be executed rather than how it should be executed.
In this paradigm, we express the logic of a computation without considering its control flow. The
declarative paradigm can be further classified into:
1. Logical Programming Paradigm: It is based on formal logic where the program statements
express the facts and rules about the problem in the logical form.
2. Functional Programming Paradigm: Programs are created by applying and composing
functions in this paradigm.
3. Database Programming Paradigm: To manage data and information organized as fields,
records, and files, database programming models are utilized.
13. What is the difference between Structured Programming and Object Oriented
Programming?
Structured Programming is a technique that is considered a precursor to OOP and usually consists of
well-structured and separated modules. It is a subset of procedural programming. The difference
between OOPs and Structured Programming is as follows:
Object-Oriented Programming Structural Programming

A program’s logical structure is provided by structural


Programming that is object-oriented is built
programming, which divides programs into their
on objects having a state and behavior.
corresponding functions.

It follows a bottom-to-top approach. It follows a Top-to-Down approach.

Restricts the open flow of data to authorized No restriction to the flow of data. Anyone can access
parts only providing better data security. the data.

Enhanced code reusability due to the Code reusability is achieved by using functions and
concepts of polymorphism and inheritance. loops.

Methods work dynamically, making calls


Functions are called sequentially, and code lines are
based on object behavior and the need of
processed step by step.
the code at runtime.

Modifying and updating the code is easier. Modifying the code is difficult as compared to OOPs.

Data is given more importance in OOPs. Code is given more importance.

14. What are some commonly used Object Oriented Programming Languages?
OOPs paradigm is one of the most popular programming paradigms. It is widely used in many
popular programming languages such as:
 C++
 Java
 Python
 JavaScript
 C#
 Ruby
15. What are the different types of Polymorphism?
Polymorphism can be classified into two types based on the time when the call to the object or
function is resolved. They are as follows:
1. Compile Time Polymorphism
2. Runtime Polymorphism
Types of Polymorphism

A) Compile-Time Polymorphism
Compile time polymorphism, also known as static polymorphism or early binding is the type of
polymorphism where the binding of the call to its code is done at the compile time. Method
overloading or operator overloading are examples of compile-time polymorphism.
B) Runtime Polymorphism
Also known as dynamic polymorphism or late binding, runtime polymorphism is the type of
polymorphism where the actual implementation of the function is determined during the runtime or
execution. Method overriding is an example of this method.
16. What is the difference between overloading and overriding?
A compile-time polymorphism feature called overloading allows an entity to have numerous
implementations of the same name. Method overloading and operator overloading are two
examples.
Overriding is a form of runtime polymorphism where an entity with the same name but a different
implementation is executed. It is implemented with the help of virtual functions.
17. Are there any limitations on Inheritance?
Yes, there are more challenges when you have more authority. Although inheritance is a very
strong OOPs feature, it also has significant drawbacks.
 As it must pass through several classes to be implemented, inheritance takes longer to process.
 The base class and the child class, which are both engaged in inheritance, are also closely
related to one another (called tightly coupled). Therefore, if changes need to be made, they may
need to be made in both classes at the same time.
 Implementing inheritance might be difficult as well. Therefore, if not implemented correctly,
this could result in unforeseen mistakes or inaccurate outputs.
18. What different types of Inheritance are there?
Inheritance can be classified into 5 types which are as follows:

1. Single Inheritance: Child class derived directly from the base class
2. Multiple Inheritance: Child class derived from multiple base classes.
3. Multilevel Inheritance: Child class derived from the class which is also derived from another
base class.
4. Hierarchical Inheritance: Multiple child classes derived from a single base class.
5. Hybrid Inheritance: Inheritance consisting of multiple inheritance types of the above
specified.
Note: Type of inheritance supported is dependent on the language. For example, Java does not
support multiple inheritance.
19. What is an interface?
A unique class type known as an interface contains methods but not their definitions. Inside an
interface, only method declaration is permitted. You cannot make objects using an interface. Instead,
you must put that interface into use and specify the procedures for doing so.
20. How is an abstract class different from an interface?
Both abstract classes and interfaces are special types of classes that just include the declaration of the
methods, not their implementation. An abstract class is completely distinct from an interface, though.
Following are some major differences between an abstract class and an interface.
Abstract Class Interface

A class that is abstract can have both abstract and non- An interface can only have abstract
abstract methods. methods.

An abstract class can have final, non-final, static and non- The interface has only static and final
static variables. variables.

An interface supports multiple


Abstract class doesn’t support multiple inheritance
inheritance.

21. How much memory does a class occupy?


Classes do not use memory. They merely serve as a template from which items are made. Now,
objects actually initialize the class members and methods when they are created, using memory in
the process.
22. Is it always necessary to create objects from class?
No. If the base class includes non-static methods, an object must be constructed. But no objects need
to be generated if the class includes static methods. In this instance, you can use the class name to
directly call those static methods.
23. What is the difference between a structure and a class in C++?
The structure is also a user-defined datatype in C++ similar to the class with the following
differences:
 The major difference between a structure and a class is that in a structure, the members are set
to public by default while in a class, members are private by default.
 The other difference is that we use struct for declaring structure and class for declaring a class
in C++.

24. What is Constructor?


A constructor is a block of code that initializes the newly created object. A constructor resembles an
instance method but it’s not a method as it doesn’t have a return type. It generally is the method
having the same name as the class but in some languages, it might differ. For example:
In python, a constructor is named __init__.
In C++ and Java, the constructor is named the same as the class name.
Example:
C++JavaPython
class base {
public:
base() { cout << "This is a constructor"; }
}
25. What are the various types of constructors in C++?
The most common classification of constructors includes:
1. Default Constructor
2. Non-Parameterized Constructor
3. Parameterized Constructor
4. Copy Constructor
1. Default Constructor
The default constructor is a constructor that doesn’t take any arguments. It is a non-parameterized
constructor that is automatically defined by the compiler when no explicit constructor definition is
provided.
It initializes the data members to their default values.
2. Non-Parameterized Constructor
It is a user-defined constructor having no arguments or parameters.
Example:
C++JavaPython
class base {
base()
{
cout << "This is a non-parameterized contructor";
}
}
3. Parameterized Constructor
The constructors that take some arguments are known as parameterized constructors.
Example:

C++JavaPython
class base {
public:
int base;
base(int var)
{
cout << "Constructor with argument: " << var;
}
};
4. Copy Constructor
A copy constructor is a member function that initializes an object using another object of the same
class.
Example:
C++Java
class base {
int a, b;
base(base& obj) // copy constructor
{
a = obj.a;
b = obj.b;
}
}

In Python, we do not have built-in copy constructors like Java and C++ but we can make a
workaround using different methods.
26. What is a destructor?
A destructor is a method that is automatically called when the object is made of scope or destroyed.
In C++, the destructor name is also the same as the class name but with the (~) tilde symbol as the
prefix.
In Python, the destructor is named __del__.
Example:
C++Python
class base {
public:
~base() { cout << "This is a destructor"; }
}

In Java, the garbage collector automatically deletes the useless objects so there is no concept of
destructor in Java. We could have used finalize() method as a workaround for the java destructor but
it is also deprecated since Java 9.
27. Can we overload the constructor in a class?
Yes We can overload the constructor in a class in Java. Constructor Overloading is done when we
want constructor with different constructor with different parameter(Number and Type).
28. Can we overload the destructor in a class?
No, a destructor cannot be overloaded in a class. There can only be one destructor present in a
class.
29. What is the virtual function?
A virtual function is a function that is used to override a method of the parent class in the derived
class. It is used to provide abstraction in a class.
In C++, a virtual function is declared using the virtual keyword,
In Java, every public, non-static, and non-final method is a virtual function.
Python methods are always virtual.
Example:
C++JavaPython
class base {
virtual void print()
{
cout << "This is a virtual function";
}
}
30. What is pure virtual function?
A pure virtual function, also known as an abstract function is a member function that doesn’t
contain any statements. This function is defined in the derived class if needed.
1. What Are OOPs?
This is one of the most commonly asked OOPs interview questions. Object-Oriented
Programming is a programming paradigm that uses objects instead of functions and procedures.
These objects are grouped into classes. OOP incorporates real-world entities like inheritance,
polymorphism, and encapsulation into programming, allowing for the integration of data and
methods.

2. Why Use OOPs?


OOPs need to be used for several reasons:

 OOP organizes code into objects, making complex problems easier to understand and solve.

 Properties and methods from parent classes are inherited by child classes, promoting efficient
code reuse.

 By using inheritance and creating reusable objects, OOP minimizes code duplication.

 OOP bundles data and the functions that manipulate it within a single unit or object.

 Access modifiers in OOP control the visibility of internal object details, enhancing security and
reducing system complexity.

 OOP allows breaking down complex problems into smaller, manageable subproblems
represented by objects.

 It allows objects from different classes to be treated as objects of a common superclass,


increasing code flexibility and extensibility.

3. What Are Some Major Object-Oriented


Programming Languages?
This is a frequently asked OOP interview question. Some major Object-Oriented Programming
languages include:

 Java
 C++

 C#

 Python

 Ruby

 JavaScript

 Swift

 PHP

 Objective-C

4. What Are the Main Features of OOPs?


The following are the main features of OOPs:

 Classes: Classes in OOP are essential components, acting as templates for objects. They
define the data structure and behavior of objects, encapsulating attributes and methods to
provide a modular and organized design framework.

 Objects: In OOP, objects are core elements that represent real-world entities with distinct
attributes and behaviors. As instances of classes, they encapsulate data and methods,
enhancing code modularity and organization. Objects communicate via well-defined interfaces,
supporting structured design principles.

 Inheritance: Inheritance enables a class to inherit fields and methods from another class,
fostering code reuse and creating a hierarchical class structure.

 Abstraction: In OOP, abstraction simplifies complex systems by creating classes modeled on


real-world entities, emphasizing essential features and concealing unnecessary details. This
approach makes clear and concise designs, allowing developers to focus on core attributes
and behaviors without the intricacies of implementation.

 Encapsulation: Encapsulation combines data and methods that operate on that data into a
single unit called a class. It also restricts direct access to some of an object’s components.

 Polymorphism: Polymorphism, a key feature of OOP, allows objects from different classes to
be treated as objects of a common base class.
5. What Is an Object?
An object in Object-Oriented Programming is a fundamental unit representing real-world entities.
It is an instance of a class, with memory allocated only upon instantiation (object creation).
Objects possess identity, state, and behavior, containing data and code to manipulate it.
Interaction between objects doesn't require knowledge of each other's data or code specifics,
just the types of messages accepted and responses provided.

6. What Is a Class?
A class is a user-defined data type that consists of data members and member functions
accessible through an instance of the class. It represents the common properties or methods of
all objects of a specific type, functioning as a blueprint for an object.

7. What Is the Difference Between a Class and a


Structure?
This is one of the most commonly asked OOPs interview questions. Here are the differences
between a class and a structure:

Feature Class Structure

Supports public, private, and Typically only supports public access


Access Modifiers
protected access modifiers. modifiers (implementation-dependent).

Supports inheritance (single or Does not support inheritance (except in


Inheritance multiple, depending on the C++, where it supports single
language). inheritance).

Does not have constructors or


Constructor/Destructor Has constructors and destructors.
destructors.

Supports method overloading


Method Overloading Supports method overloading.
(implementation-dependent).

Supports method overriding (in case


Method Overriding Does not support method overriding.
of inheritance).
Members are private by default (in
Default Members Members are public by default.
most languages).

Can have a size larger than the sum


Size is equal to the sum of its members'
Size of its members (due to additional
sizes.
metadata).

Structures are typically allocated on the


Objects are typically allocated on
Memory Allocation stack or embedded in other data
the heap.
structures.

Used for complex data types and to Used for simple, lightweight data types
Recommended Usage
model real-world entities. and grouping-related data.

8. What Are the Differences Between Class and


Object?
The primary differences between a class and an object in Object-Oriented Programming are:

Aspect Class Object

A class is a template or blueprint that


An object is a specific instance of a class
Definition defines the attributes and actions of
created from the class blueprint.
objects.

Memory A class itself does not occupy any Objects occupy memory space when they
Allocation memory space. are created.

Objects are created from classes at


Classes are created by the programmer
Creation runtime, typically using constructors or
during the design phase.
object creation expressions.

An object has its own copies of the


Properties and A class defines the properties and properties and can access and modify
Methods methods that objects will have. them. It also has access to the methods
defined in the class.

Objects can be instantiated from a class


Instantiation A class cannot be instantiated directly. using the new keyword or object creation
expressions.

Objects are the actual entities that exist and


Purpose A class serves as a blueprint or template.
perform tasks during runtime.
Classes can have access modifiers Objects do not have access modifiers; they
Access Modifiers (public, private, protected) that control access members based on the access
access to their members. modifiers defined in the class.

Classes can inherit properties and Objects cannot inherit directly from other
Inheritance methods from other classes through objects but from the class they are
inheritance. instantiated from.

Classes support polymorphism, allowing Objects can exhibit polymorphic behavior


Polymorphism objects of different classes to be treated based on the class they are instantiated
as objects of a common superclass. from.

9. What Are Some Advantages of Using OOPs?


Some of the primary advantages of OOPs are as follows:

 Code Reusability: Utilizes class-based architecture for modular design, enabling instantiation
of objects from reusable class templates. This promotes code efficiency through multiple
instantiations.

 Data Redundancy Management: Implements controlled redundancy for data integrity,


facilitates data consistency across multiple instances, and utilizes inheritance for shared class
definitions.

 Enhanced Security: Implements encapsulation for data protection, utilizes access modifiers
to control the visibility of class members and employs abstraction to expose only necessary
interfaces.

 Improved Design Methodology: Facilitates comprehensive design phase, supports scalable


architecture for complex systems, and provides flexibility in handling system growth beyond
the initial scope.

 Efficient Debugging: Utilizes self-contained objects for localized error isolation, implements
exception handling for robust error management, and reduces code duplication, minimizing
potential error sources.

 Polymorphism: Enables method overloading and overriding, supports runtime polymorphism


through interface implementation, and enhances code flexibility and extensibility.
10. What Is the Difference Between Object-
Oriented and Structured Programming?
Here are the main differences between them:

Aspect Object-Oriented Programming Structured Programming

OOP focuses on creating objects that Structured Programming focuses on writing


Approach
contain data and behavior. The program a set of instructions or functions to perform
is organized around objects and their tasks. The program is organized around
interactions. procedures or functions.

In OOP, data and functions are combined


In Structured Programming, data and
Data and into objects. Data is encapsulated within
functions are separate entities. Functions
Functions objects, and functions (methods) operate
operate on data passed as arguments.
on that data.

Code is organized around classes and Code is organized around procedures or


Code
objects, promoting code reuse and functions, often leading to monolithic and
Organization modularity. less modular code.

OOP supports data abstraction and Structured Programming has limited


Data
encapsulation, where implementation support for data abstraction and
Abstraction details are hidden from the user. encapsulation.

Structured Programming does not support


Inheritance OOP supports inheritance.
inheritance.

Structured Programming does not support


Polymorphism OOP supports polymorphism.
polymorphism.

Structured Programming has limited code


OOP promotes code reuse through the
Code Reuse reuse capabilities, often achieved through
inheritance and composition of objects.
function libraries or modules.

11. What Other Paradigms of Programming Exist


Besides OOPs?
This is one of the most commonly asked OOPs interview questions. Programming paradigms
categorize programming languages based on their core characteristics.

There are two main types:

 Imperative Programming Paradigm

 Declarative Programming Paradigm

These paradigms can be further subdivided:

 Imperative Programming Paradigm: This approach specifies how to execute program logic
and defines a sequence of commands to change program state. It includes:
 Procedural Programming Paradigm: This method defines a set of computational
steps to be carried out and executed in order from top to bottom.

 Object-Oriented Programming: This organizes software design around data or


objects rather than functions and logic.

 Parallel Programming: This focuses on breaking down tasks into smaller components
that can be processed concurrently.

 Declarative Programming Paradigm: This approach emphasizes what the program should
accomplish without explicitly specifying control flow. It includes:

 Logical Programming Paradigm: Based on formal logic, this uses a set of statements
expressing facts and rules to solve problems.

 Functional Programming Paradigm: This builds programs by composing and applying


functions, avoiding changing-state and mutable data.

 Database Programming Paradigm: This model manages data organized into fields,
records, and files.

12. What Are the Differences Between Procedural


and Object-Oriented Programming?
The following are the differences between Procedural Programming and Object-Oriented
Programming:

Aspect Procedural Programming Object-Oriented Programming

Data Separate from procedures Encapsulated within objects

Program structure Top-down approach Divided into objects

Data access Usually global Private (encapsulated)

Code reusability Limited, mainly through functions High, through inheritance

Data security Less secure More secure due to encapsulation


Overloading Generally not supported Supports function and operator overloading

Complexity Simpler for small programs Better for managing complex programs

Modularity Less modular Highly modular

Abstraction level Low level of abstraction High level of abstraction

Inheritance Not supported Supported

Polymorphism Not supported Supported

Examples C, Pascal Java, C++, Python, C#

13. What Are Access Specifiers, and When


Should We Use These?
This is a popular OOP interview question. As the name indicates, access specifiers are special
types of keywords used to specify or control the accessibility of entities such as classes and
methods.

The three primary access specifiers are:

 Public

 Private

 Protected

When to use each:

 Public: Use when you want class members to be accessible from anywhere in the program.
They are typically used for methods that need to be called by external code or for data that
should be freely accessible.

 Private: Use when you want to restrict access to class members only within the same class.
Helps in hiding implementation details and maintaining data integrity. Useful for internal helper
methods or variables that should not be directly manipulated from outside the class.
 Protected: Use when you want to allow access to class members within the same class and
its subclasses. Useful when implementing inheritance and you want to share some internal
functionality with derived classes.

14. What Is Encapsulation?


Think of encapsulation like a capsule. You see a simple shell on the outside, but inside, it
contains everything needed to do its job. In programming, encapsulation works similarly:

 It bundles related data and functions together into a single unit (like a class).

 It hides the complex internal functioning and shows only what's necessary to use it.

15. What Is Abstraction?


This is one of the frequently encountered OOPs interview questions. A typical OOPs interview
question, this one is often asked. Abstraction in Object-Oriented Programming hides non-
essential information and shows only what is necessary to users. This is key to representing real -
world objects simply for easy user interaction.

There are two types of abstractions in Object-Oriented Programming:

 Data Abstraction: Data abstraction is the most simple implementation of abstraction. When
dealing with many complex processes, we hide unnecessary data and display only the
information necessary for the users.

 Process Abstraction: When we hide the internal implementation and do not disclose all the
details about a method or function to the users, this is known as process abstraction. Instead
of dealing with data, we deal with their process in this type of abstraction.

16. What Are Some Recommended Best


Practices for Applying Abstraction in Your
Code?
This is a common OOPs interview question that is regularly asked. Here are a few best practices
for using abstraction in your code:

 Creating well-defined interfaces or abstract classes.

 Keeping designs simple and avoiding over-engineering.

 Prioritizing composition over inheritance.

17. What Is Polymorphism?


This is one of the most commonly asked OOPs interview questions. Polymorphism is a core
concept in Object-Oriented Programming that allows objects of various types to be treated in a
uniform way. It makes code more flexible and reusable. It allows for writing methods that can
work with objects of multiple types as long as they share a common superclass or interface.

For example, you could have a method that processes "Shape" objects, and it would work
correctly whether you pass it a "Circle," "Square," or "Triangle" object, as long as they're all
subclasses of "Shape."

18. What Are the Different Types of


Polymorphism?
There are two main types of polymorphism in Object-Oriented Programming:

 Compile-Time Polymorphism (Static Polymorphism)

 Also known as method overloading.

 Resolved during compile time.

 Occurs when multiple methods in the same class have the same name but different
parameters.

 The compiler specifies which method to call based on the method signature.

 Runtime Polymorphism (Dynamic Polymorphism):


 Also known as method overriding.

 Resolved during runtime.

 Occurs when a subclass gives a specific implementation for a method already defined
in its superclass.

 The JVM determines which method to call based on the object's actual type at runtime.

19. What Is Method Overloading?


When a class has multiple methods with the same name but different parameters, it is called
Method Overloading.

Characteristics of method overloading:

 Same Method Name: All overloaded methods share the same name within a class.

 Different Parameters: The methods must differ in the number, type, or order of parameters.

 Return Type: The return type can be different, but this alone is not enough to overload a
method.

 Compile-Time Polymorphism: Method overloading in Java is resolved at compile time, not at


runtime.

Let’s understand this with an example in Java:

class Calculator {
public int add(int a, int b) {
return a + b;
}

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


return a + b + c;
}

public double add(double a, double b) {


return a + b;
}
}
20. What Is Method Overriding?
This is a standard OOPs interview question. When a subclass (child class) in Java implements a
method that has the same name and parameters as a method in its parent class, this is called
method overriding.

Characteristics of method overriding:

 Same Method Signature: The method in the subclass that overrides a method from the
superclass must have the same name, return type, and parameter list as the method in the
superclass.

 Runtime Polymorphism: The decision about which method to call is made at runtime, not at
compile time.

 Access Modifiers: The overriding method must not have a stricter access level than the
overridden method.

Let’s understand this with an example in Java:

class Shape {
double getArea() {
return 0;
}
}

class Circle extends Shape {


private double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double getArea() {
return Math.PI * radius * radius;
}
}

class Rectangle extends Shape {


private double width, height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

@Override
double getArea() {
return width * height;
}
}

public class Main {


public static void main(String[] args) {
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);

System.out.println("Circle area: " + shape1.getArea());


System.out.println("Rectangle area: " + shape2.getArea());
}
}

21. What Is the Difference Between Overloading


and Overriding?
This is one of the most commonly asked OOPs interview questions. Here's the difference
between overloading and overriding:

Aspect Overloading Overriding

Methods with identical names and Implementing a method in a subclass that is


Definition
differing parameters. already defined in its superclass.

Provides method implementation Allows subclasses to provide specific


Purpose
flexibility. implementation.

Occurs within the same class or


Class Occurs between superclass and subclass.
between parent and child classes.

Method Must have different parameter types or Must have the same method signature (name
Signature a number of parameters. and parameters).

Return Type Can be different Must be the same or covariant


Access
Can be different Cannot be more restrictive in the subclass
Modifier

Static/Non-
Can be either Must be non-static
static

Binding Compile-time (static) binding Runtime (dynamic) binding

22. What Is the Difference Between Compile-Time


Polymorphism and Runtime Polymorphism?
Here's the difference between compile-time polymorphism and runtime polymorphism:

Aspect Compile-Time Polymorphism Runtime Polymorphism

Resolution Time Compile time Runtime

Also Known As Static binding, early binding Dynamic binding, late binding

Implementation Method overloading, operator overloading Method overriding, Inheritance

Flexibility Less flexible More flexible

Performance Generally faster Slightly slower due to runtime resolution

Decision Making Before program execution During program execution

Type Checking Done by compiler Done at runtime

23. Is It Possible to Achieve Runtime


Polymorphism Through Data Members in Java?
No, runtime polymorphism cannot be achieved by data members in languages like Java or C++
because:

 Runtime polymorphism is achieved through method overriding, not data members (variables).

 Methods can be overridden, but data members cannot be overridden.


 When accessing a data member using a reference variable of the parent class that refers to a child class
object, the data member of the parent class will always be accessed.

 This is because data members are not overridden, so runtime polymorphism doesn't apply to them.

 What occurs with data members is actually called "hiding" rather than overriding.

24. What Is Inheritance?


Inheritance in Object-Oriented Programming describes the ability of a class to inherit features from a
superclass.

Syntax:
class SubClass extends SuperClass {
// SubClass members
}

Key elements of the syntax:

 Use the keyword class to declare a new class.

 After the class name, use the keyword extends.

 Following extends, specify the name of the superclass (parent class).

 The subclass body is enclosed in curly braces .

25. What Is a Superclass?


The superclass is the class that provides features inherited by a subclass, also known as the base
class or parent class.

26. What Is a Subclass?


A subclass is a class that inherits all members (fields, methods, and nested classes) from
another class, also known as a derived class, child class, or extended class.
27. What Different Types of Inheritance Are
There?
This is a common OOPs interview question that is regularly asked. In Object -Oriented
Programming, inheritance is categorized by the relationship between the derived class and its
superclass.

 Single inheritance

 Multiple inheritance

 Multilevel inheritance

 Hierarchical inheritance

 Hybrid inheritance

28. Are There Any Limitations on Inheritance?


This is one of the frequently encountered OOPs interview questions. Despite its strength in
Object-Oriented Programming, inheritance does have its set of limitations:

 Performance Overhead: Inherited methods typically execute more slowly than regular functions due to
the additional layer of indirection.

 Potential for Misuse: Incorrect application of inheritance can result in flawed or inappropriate solutions
to programming problems.

 Inefficient Resource Utilization: Base classes may contain data members that remain unused in
derived classes, potentially leading to unnecessary memory consumption.

 Increased Interdependence: Inheritance creates a tighter coupling between parent and child classes.
Modifications to the base class can have far-reaching effects on all its descendants.

29. Why Is Inheritance Used in Java?


Inheritance is an essential feature in Object-Oriented Programming languages like Java and C++.
Inheritance is like a parent passing traits to their child. In programming, it lets one class (the
child) get all the characteristics and abilities of another class (the parent). This means the ch ild
class can use the parent's data and functions without rewriting them.
The main idea is to make new classes based on existing ones. The new class (child) gets everything
from the old class (parent) and can add its unique features.

With inheritance, we'd save time writing the same code repeatedly for similar classes. It's like
reinventing the wheel each time instead of just using a wheel that already exists.

30. How to Implement Inheritance in Java?


Inheritance can be implemented by using:

 extends: Used to create inheritance between two classes.

 implements: Used to create inheritance between a class and an interface.

31. Is It Possible for a Class to Extend Itself?


It's not possible for a class to extend itself.

32. What Is Composition?


Composition is a design approach in Object-Oriented Programming to establish a has-a
relationship between objects. In Java, this is done by including instance variables of other
objects within a class.

33. What Is the Difference Between Aggregation


and Composition?
Aggregation: Aggregation represents a weak association between two entities where one entity can
contain or use another, but the contained entity can exist independently. It's characterized by:
 A relationship where the contained entity can exist without the container.

 The ability for the contained entity to be associated with multiple containers.

 No direct control of the contained entity's lifespan by the container.

 Implementation typically using references or pointers to existing objects.

Example in Java:

Composition: Composition denotes a strong, whole-part relationship between two entities where
the part cannot exist without the whole.

Key characteristics include:

 The part is an integral component of the whole and cannot exist independently.

 The whole is responsible for the creation and destruction of its parts.

 A part typically belongs to only one whole at a time.

 Implementation often involves creating part objects within the whole's constructor.

Example in Java:

The major differences include:

 Entity Independence: Aggregated entities can exist independently; composed entities cannot.

 Relationship Exclusivity: Aggregated entities can be shared; composed entities typically


belong to one whole.

 Lifespan Management: Aggregating objects don't control the lifespan of aggregated entities;
composing objects do control the lifespan of their parts.

 Coupling: Aggregation results in loose coupling, while composition creates tighter coupling
between entities.
34. What Is the Difference Between Inheritance
and Polymorphism?
Following are the differences between inheritance and polymorphism:

Aspect Inheritance Polymorphism

A mechanism where a class inherits


Objects of different types that are treated
Definition properties and behaviors from another
as objects of a common base type.
class.

Code reuse and establishing a hierarchical Flexibility in using different object types
Purpose
relationship between classes. through a common interface.

Establishes an "is-a" relationship between Enables "one interface, multiple


Relationship
classes. implementations".

Achieved using the extends keyword (in Achieved through method overriding and
Implementation
many languages). interfaces/abstract classes.

Single inheritance, multiple inheritance Runtime polymorphism, compile-time


Types
(in some languages). polymorphism.

Creates tight coupling between parent and Promotes loose coupling through
Coupling
child classes. abstraction.

Focus Emphasizes sharing of code and behavior. Emphasizes interchangeability of objects.

35. Can You Call the Base Class Method Without


Creating an Instance?
Often asked, this OOPs interview question is common. In Object-Oriented Programming
languages like C#, instance methods of a base class are tied to specific objects and cannot be
invoked without an instance. This means you typically need to create an object of either the base
class or a derived class to call these methods. However, static methods in a base class operate
at the class level rather than the instance level. These can be called directly using the cla ss
name, without the need to instantiate an object.
36. What Is a Constructor?
Constructors are special methods or functions in Object-Oriented Programming used to initialize
class objects, defining their initial state and creation method. They typically s hare the same
name as their class.

37. How Many Types of Constructors Are Used in


Java?
Constructors in Java are classified into three types:

 No-Arg constructor

 Parameterized constructor

 Default constructor

38. What Is the Purpose of a Default


Constructor?
The purpose of a default constructor is to:

 Initialize an object to a default state when no arguments are provided during object creation.

 Ensure that an object can be created without explicitly specifying initial values.

 Provide a fallback initialization method if no other constructors are called.

 Allow the class to be instantiated in arrays or collections that require a no-argument


constructor.

 Enable derived classes to have a default superclass constructor to call.

39. Does the Constructor Return Any Value?


Constructors are special functions in Object-Oriented Programming that initialize newly created
objects. Unlike regular methods, constructors don't have a return type and are implicitly called
when an object is instantiated. Their primary purpose is to set up the initial state of an object by
initializing instance variables.

Constructors share the same name as their class and can be overloaded to accept different
parameters. While they resemble methods in some ways, constructors are distinct in that th ey
can't be directly called and aren't part of the object's interface.

Many languages provide a default no-argument constructor if none is explicitly defined, and
constructors can often chain to other constructors or superclass constructors to build comple x
initialization sequences.

40. Can We Overload the Constructor in a Class?


Yes, we can overload constructors in a class. Constructor overloading indeed works similarly to
function overloading. The key aspects are:

 Same Name: All constructors have the same name as the class.

 Different Parameters: Overloaded constructors differ in their parameter lists.

 Automatic Selection: The appropriate constructor is called based on the arguments provided
during object creation.

Here's an example demonstrating constructor overloading in Java:


This example shows three overloaded constructors for the Rectangle class:

 A no-argument constructor that sets both dimensions to 0.

 A one-argument constructor that creates a square.

 A two-argument constructor that sets length and width separately.

The appropriate constructor is automatically called based on the arguments provided when
creating new Rectangle objects.

41. What Is Constructor Chaining?


Constructor chaining in Object-Oriented Programming is the method of using one constructor to
invoke another within the same class. This approach helps simplify the program by minimizing
redundant code.

Constructor chaining can be achieved in two ways:

 Within the Same Class: Use this for chaining constructors within the same class.

 From the Base Class: Use superfor chaining constructors from different classes (parent and
child).

42. What Are the Differences Between the


Constructor and the Method in Java?
Constructors and methods are fundamental components of Object-Oriented Programming, but
they serve different purposes and have distinct characteristics.

 Invocation:

 Constructor: A constructor is invoked implicitly when an object is created using the


new keyword.

Person person = new Person();


 Method: A method is invoked explicitly by the programmer through method calls.

person.setName("peter");

 Naming:

 Constructor: The name of a constructor must be the same as the name of the class in
which it is defined.

 Method: A method can have any name, except it cannot be the same as the class
name if it has a return type.

 Return Type:

 Constructor: Constructors do not have a return type, not even void. The object being
constructed is implicitly returned.

 Method: Methods must have a return type, which can be a primitive type, an object
type, or void if no value is returned.

 Inheritance:

 Constructor: Constructors are not inherited by subclasses. Each class must define its
own constructors.

 Method: Methods can be inherited by subclasses and can be overridden to provide


specific behavior in the subclass.

 Object Initialization:

 Constructor: A constructor initializes an object that does not yet exist. It sets up the
initial state of the object.

 Method: A method performs operations on an already existing object. It can manipulate


the object's state or perform actions using the object's data.

Here is an example demonstrating the differences between a constructor and a method:


public class Example {
private String name;
private int age;
// Constructor
public Example(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
// Creating an object using the constructor
Example example = new Example("Jimmy", 30);
// Calling a method on the created object
example.displayInfo();
}
}

43. What Is a Destructor?


A destructor in Object-Oriented Programming is a method that is triggered automatically right
before an object's memory is deallocated. This can happen when the object’s scope ends, is
contained within another object whose lifetime ends, or is dynamically allocated and explicitly
freed.

Note : Test your web and mobile apps across 3000+ real desktop browsers. Leading digital
experience testing for insurance sector.

OOPs Interview Questions for


Experienced
Studying the Scrum Master interview questions outlined in this tutorial will equip you with the
right approach to effectively prepare for this job role.

1. How to Implement Abstraction in Java?


There are two methods to implement abstraction in Java:
 Abstract class

 Interface

2. What Is an Abstract Class?


An abstract class is a template definition of methods and variables for a particular class or
category of objects. In programming, objects are code units, and each object belongs to a
generic class.

Abstract classes contain one or more abstract methods or behaviors. Abstracting o bjects or
classes means summarizing their characteristics relevant to the current program's operation.
Abstract classes are utilized in all Object-Oriented Programming languages, including Java, C++,
C#, and VB.NET.

3. Explain the Interface.


In Object-Oriented Programming, an interface is a contract that defines a set of abstract methods
and constants that a class must implement. It serves as a blueprint for classes, specifying what
methods should be available without dictating how these methods should be i mplemented.

Characteristics of interface include:

 Interfaces contain method signatures without implementations. Classes that implement an


interface must provide concrete implementations for all its methods.

 Unlike classes in many OOP languages, a single class can implement multiple interfaces,
allowing for a form of multiple inheritance.

 Interfaces enable loose coupling between different parts of a system, as classes can depend
on interfaces rather than concrete implementations.

 Objects of different classes implementing the same interface can be treated uniformly,
enhancing code flexibility.

 Interfaces act as contracts between different system components, clearly defining expected
behavior.
4. How Is an Abstract Class Different From an
Interface?
This is one of the frequently encountered OOPs interview questions. The reason is that abstract
classes can contain non-final variables, while variables in an interface are final, public, and
static.

interface SimpleInterface {
int CONSTANT = 100; // implicitly public, static, and final
}

abstract class SimpleAbstractClass {


int variable = 100; // can be non-final and instance-specific
}

The above example shows that interfaces can only have constants, while abstract classes can
have mutable instance variables.

The following table demonstrates the difference between an abstract class and interface.

Characteristic Abstract Class Interface


Can have non-final instance
Variables Only constants (public static final).
variables.
Can have both abstract and concrete All methods are implicitly abstract (before
Methods
methods. Java 8).
Constructor Can have constructors. Cannot have constructors.
A class can extend only one abstract
Multiple Inheritance A class can implement multiple interfaces.
class.
Can use any access modifier for
Access Modifiers All members are implicitly public.
members.
Instantiation Cannot be instantiated. Cannot be instantiated.
For unrelated classes to implement
Purpose For objects that are closely related.
common behavior.
Speed Slightly faster Slightly slower due to extra indirection.
Default Method
Supported Supported (from Java 8 onwards)
Implementation
Can have static methods (from Java 8
Static Methods Can have static methods
onwards)
Can have private methods (from Java 9
Private Methods Can have private methods
onwards).
5. Can You Declare an Interface Method Static?
No, you cannot declare an interface method as static in most Object-Oriented Programming
languages, including Java and C#. Interface methods are, by default, abstract a nd public. Static
methods belong to the class itself, not to any specific instance. The purpose of an interface is to
define a contract that implementing classes must follow, which involves instance methods.

 Interface methods are, by default, abstract and public.

 Static methods belong to the class itself, not to any specific instance.

 The purpose of an interface is to define a contract that implementing classes must follow,
which involves instance methods.

However, there are some exceptions:

 In Java 8 and later, you can have static methods in interfaces, but these are not considered
part of the interface contract. They are utility methods associated with the interface.

 In C# 8.0 and later, interfaces can have static members, including static methods, but these
are not inherited by implementing classes.

6. Can We Make Constructors Static?


No, constructors cannot be made static in most Object-Oriented Programming languages,
including Java and C#.

Constructors are specifically designed to initialize new object instances when they are created.
They set up the initial state of an object and are called automatically when an object is
instantiated using the new keyword.

Static members, on the other hand, belong to the class itself rather than to any specific instance
of the class. They can be accessed without creating an object of the class.

Making a constructor static would contradict its fundamental purpose of initializing individual
object instances. It would also conflict with object creation and initialization in Object-Oriented
Programming.
If you need class-level initialization, most languages provide other mechanisms like static
initializer blocks or static methods that can be used for this purpose.

7. What Are the Rules for Creating a


Constructor?
This is one of the frequently encountered OOPs interview questions. These are the rules to
follow while creating constructors:

 The name of the constructor must be the same as the class name.

 Constructors in Java do not have a return type, even void.

 Multiple constructors can exist in the same class, known as constructor overloading.

 Access modifiers can be used with constructors to change their visibility/accessibility.

 A default constructor is provided by Java and invoked during object creation unless you define
any constructor.

8. Can We Make the Abstract Methods Static in


Java?
No, you cannot declare abstract methods as static in Java due to the inherent contradictions
between the concepts of abstract and static methods.

9. Is It Possible to Declare an Abstract Method


With the Private Modifier?
No, an abstract method cannot be private because it must be implemented in the child class.

Declaring it as private would prevent it from being accessed and implemented outside the class.
10. What Is the Virtual Function?
In Object-Oriented Programming, such as C++, a virtual function or method is an inheritable and
overridable function dispatched dynamically. Virtual functions play a crucial role in runtime
polymorphism in OOP, enabling the execution of target functions that are not precisely identified
at compile time.

Many programming languages, including JavaScript, PHP, and Python, treat all methods as
virtual by default and do not offer a modifier to alter this behavior. However, specific languages
provide modifiers like final and private in Java and PHP to prevent methods from being
overridden by derived classes.

11. What Are the Characteristics of an Abstract


Class?
Abstract classes in Object-Oriented Programming have several key characteristics:

 Incomplete Implementation: Abstract classes can contain both fully implemented methods
and abstract methods (methods without a body).

 Cannot be Instantiated: You cannot create objects directly from an abstract class.

 Meant for Inheritance: Abstract classes are designed to be subclassed by other classes that
provide implementations for the abstract methods.

 Can Have Constructors: Although they can't be instantiated directly, abstract classes can
have constructors to initialize fields.

 May Contain Instance Variables: Abstract classes can define and initialize instance
variables.

 Can Have any Access Modifier: Methods in an abstract class can be public, protected, or
private.

 Support for Multiple Inheritance: In languages like Java, abstract classes can extend
another class and implement interfaces.

 Can Have Static Members: Abstract classes can contain static methods and variables.
 May Contain Final Methods: These cannot be overridden by subclasses.

 Provide a Common Interface: They often define a common structure for a group of related
subclasses.

12. What Are the Differences Between a Copy


Constructor and an Assignment Operator?
Here are the differences between a copy constructor and an assignment operator:
Aspect Copy Constructor Assignment Operator

Creates a new object as a copy of an Copies contents of one object to an


Purpose
existing one. existing object.

When an existing object is assigned a


When it's called When a new object is created.
new value.

ClassName(const ClassName& ClassName& operator=(const


Syntax (C++)
other) ClassName& other)

Reference to the assigned object


Returns Nothing (constructs a new object).
(usually).

Self-assignment
Not needed Often needed to handle a = a case.
check

Memory allocation Always allocates new memory. May or may not allocate new memory.

Usage with new Can be used with new. Cannot be used with new.

Inheritance Compiler-generated version is called the Compiler-generated version doesn't call


behavior base class version. the base version.

Default
Performs shallow copy. Performs shallow copy.
implementation

13. What Is the Difference Between Abstraction


and Encapsulation?
Abstraction and encapsulation are important concepts in programming. They're related but serve
different purposes:

 Encapsulation encapsulates the internal workings of an object, maintaining its state and
operations within a defined scope. Abstraction focuses on defining a clear and concise
interface for interaction.

 Abstraction simplifies software design by focusing on essential features, promoting clarity, and
reducing complexity.Encapsulation ensures that data integrity and security are maintained by
controlling access to internal states and methods.

 Encapsulation manages how data is stored and accessed internally, while Abstraction
simplifies interaction with complex systems by providing a clear, high-level view.

 While encapsulation protects data by encapsulating it within a class and providing controlled
access methods, Abstraction simplifies the representation of systems by focusing on essential
behaviors and ignoring unnecessary details.

14. How Much Memory Does a Class Occupy?


The memory occupied by a class depends on several factors:

 The size and number of data members in the class.

 Any padding added for memory alignment.

 Overhead for the class itself (e.g., vtable pointer for classes with virtual functions).

The actual memory usage can be larger than the sum of the sizes of data members due to:

 Padding between data members for alignment.

 Virtual function table pointers (in C++ for classes with virtual functions).

 Object headers (in Java).


15. What Is Coupling in OOP, and Why Is It
Helpful?
Coupling in Object-Oriented Programming refers to the degree of interdependence between
classes or modules in a software system. It measures how closely connected or dependent
different components are on each other.

There are two types of coupling:

 Tight coupling

 Loose coupling

Difference between tight coupling and loose coupling:

 Tight coupling makes testing difficult, while loose coupling makes it easier.

 Unlike tight coupling, loose coupling promotes programming to interfaces, not


implementations.

 Tight coupling makes it hard to swap code between classes; loose coupling allows for easier
swapping of modules.

 Tight coupling is inflexible to changes, whereas loose coupling supports easier modifications.

16. What Is Cohesion in OOP?


Cohesion in OOP refers to the degree to which the elements within a module or class belong
together and work towards a single, well-defined purpose. It measures how closely related and
focused the responsibilities of a single module or class are.

17. Name the Operators That Cannot Be


Overloaded.
The operators that cannot be overloaded in C++ are:
 Scope resolution operator (::)

 Ternary or conditional operator (?:)

 Member access or dot operator (.)

 Pointer-to-member operator (.*)

 Object size operator (sizeof)

 Object type operator (typeid)

 static_cast (casting operator)

 const_cast (casting operator)

 reinterpret_cast (casting operator)

 dynamic_cast (casting operator)

18. What Are the Manipulators in OOP, and How


Do They Work?
Manipulators in Object-Oriented Programming, particularly in C++, are special functions or
objects that modify input/output streams. They work by altering the formatting or behavior of
streams without changing the actual data.

Manipulators work by modifying the state or behavior of input/output streams:

 Function-Based Manipulators:

 These are functions that take a stream reference as an argument and return the same
stream reference.

 They modify the stream's internal state or flags.

 The stream's operator << or operator >> is overloaded to handle these functions.

 When encountered in an I/O statement, the manipulator function modifies the stream.

 Class-Based Manipulators:

 These are objects of classes with overloaded stream insertion/extraction operators.


 The overloaded operators modify the stream's state.

 Stream State Modification:

 Manipulators typically change internal flags or data members of the stream object.

 These modifications affect how subsequent I/O operations behave.

 Chaining:

 Manipulators can be chained in a single statement because they return the stream
object.

 This allows for multiple modifications in one line of code.

 Persistence:

 Some manipulators' effects persist until explicitly changed.

 Others (like the setw() function) affect only the next I/O operation.

 Implementation in iostream Library:

 Many manipulators are implemented as inline functions for efficiency.

 They often use stream member functions to modify the stream's state.

19. Give a Real-World Example of Polymorphism.


A real-world example of polymorphism can be found in a digital media player application. Let's
consider a music player that can handle various types of audio files:

 Base Class: AudioFile

 Properties: title, artist, duration

 Methods: play(), pause(), stop()

 Derived Classes:

 MP3File: MP3 Audio File

 WAVFile: WAV Audio File

 AADFile: Apple Audio File


Each derived class inherits from AudioFile but implements the play() method differently due to
the specific encoding and decoding requirements of each file format.

In the application:

//cpp
vector<AudioFile*> playlist;
playlist.push_back(new MP3File("Song1.mp3"));
playlist.push_back(new WAVFile("Song2.wav"));
playlist.push_back(new AADFile("Song3.aad"));

for (AudioFile* song : playlist) {


song->play(); // Polymorphic call
}

Here, the play() method is called on each song in the playlist. The actual implementation called
depends on the specific file type, demonstrating polymorphism:

 MP3File might use an MP3 decoder.

 WAVFile might directly stream the uncompressed audio.

 AADFile might use Apple's proprietary decoder.

This example shows how polymorphism allows the application to treat different audio file types
uniformly through a common interface (AudioFile) while executing the appropriate play() method
for each specific file type.

20. What Is the Difference Between a Base Class


and a Superclass?
Aspect Base Class Superclass

Definition The class from which other classes inherit. The class from which other classes inherit.

Usage Commonly used in C++ terminology. Commonly used in Java terminology.

Synonyms Parent class, superclass. Parent class, base class.


At the top or intermediate level of At the top or intermediate level of
Hierarchy
inheritance. inheritance

Purpose Provides common attributes and methods. Provides common attributes and methods.

Inheritance Other classes derive from it. Other classes extend from it.

21. What Is Data Abstraction?


Data abstraction, the most basic form of abstraction in Object-Oriented Programming, involves
manipulating complex objects where the underlying data structure or characteristics remain
hidden.

22. What Are the Levels of Data Abstraction?


There are three main levels of data abstraction in OOP:

 Physical or Implementation Level:

 This is the lowest level of abstraction.

 It deals with how data is actually stored and managed in memory.

 This level is typically hidden from the user and handled by the programming language
or runtime environment.

 Logical or Class Level:

 This is the intermediate level of abstraction.

 It defines the structure and behavior of objects through classes.

 It includes the attributes (data members) and methods (member functions) that make up
a class.

 This level is where the programmer defines the blueprint for objects.

 View or Interface Level:

 This is the highest level of abstraction.

 It defines how users or other parts of the program interact with objects.
 This level typically includes public methods and properties that are accessible to users
of the class.

 It hides the internal implementation details and exposes only what's necessary for using
the object.

23. What Are the Types of Variables in OOP?


There are three main types of variables in Object-Oriented Programming:

 Instance variables (also called object variables)

 Class variables (also called static variables)

 Local variables

24. Is It Possible to Overload a Constructor?


Yes, it's possible to overload a constructor.

25. Can We Overload the Main() Method in Java


and Give an Example?
In Java, you can't truly overload the main() method in the sense of having
multiple main() methods that the JVM will recognize as entry points for your program. However,
you can have multiple methods named main() with different parameter lists within the same
class. The JVM will only use the standard main(String[] args) as the entry point.

Here's an example to understand this:


public class MainOverloadExample {
// The actual entry point recognized by JVM
public static void main(String[] args) {
System.out.println("Main method called with String[] args");

// Calling other "main" methods


main();
main(5);
main("Hello");
}

// Overloaded main methods (not entry points)


public static void main() {
System.out.println("Main method with no arguments");
}

public static void main(int number) {


System.out.println("Main method with int argument: " + number);
}

public static void main(String str) {


System.out.println("Main method with String argument: " + str);
}
}

Important points to note:

 Only public static void main(String[] args) serves as the program's entry point.

 Other main methods are treated as regular methods and can be called from within the
program.

 These additional main() methods don't affect how the program is started by the JVM.

 This approach can help organize code or provide different ways to process input, but it's not
true method overloading from the JVM's perspective.

26. What Do You Understand by Copy


Constructor in Java?
In Java, there is no explicit copy constructor like in C++. Instead, Java provides a default
implementation of object copying through the assignment operator (=) and the constructor that
takes an object of the same class as a parameter.

When you create a new object by assigning an existing object to it, Java perfo rms a shallow copy
by default. A shallow copy creates a new object and copies the reference values of the instance
variables from the original object to the new object. This means that both objects will share the
same reference to mutable objects (objects that can be modified after creation, such as arrays or
other custom objects).

Here's an example to illustrate object copying in Java:

To create a copy constructor, start by defining a constructor that accepts an object of the same
type as its parameter:

public class WebPage {


private String url;
private int loadTime;

public WebPage(WebPage webPage) {


}
}

Afterward, each field of the input object is copied into the new instance:

public class WebPage {


private String url;
private int loadTime;

public WebPage(WebPage webPage) {


this.url = webPage.url;
this.loadTime = webPage.loadTime;
}
}

What we have here is a shallow copy, which is suitable because all our fields —such
as String and int—are either primitive types or immutable types.

If the Java class contains mutable fields, an alternative approach in its copy constructor is to
perform a deep copy. This ensures that the newly created object is independent of the original
one by creating distinct copies of each mutable object:

public class WebPage {


private String url;
private int loadTime;
private Map<String, String> pageElements;
public WebPage(WebPage webPage) {
this.url = webPage.url;
this.loadTime = webPage.loadTime;
this.pageElements = new HashMap<>(webPage.pageElements);
}
}

27. What Are the Differences Between a Copy


Constructor and a Clone?
In Java, the clone method allows us to create an object from an existing object, but the copy
constructor offers several advantages:

 Implementing a copy constructor is simpler; there's no need to


handle CloneNotSupportedException or implement the Cloneable interface.

 Unlike clone, which returns a general object reference requiring typecasting, the copy
constructor directly returns the appropriate type.

 Copy constructors can assign values to final fields, which is impossible with the clone method.

28. What Is the Static Variable?


When a variable is declared static, a single class-level copy is created and shared among all
objects. This makes static variables effectively global variables shared across all class instances.

Some important points about static variables are:

 All objects of the class access the same copy of a static variable.

 Static variables conserve memory as they are not duplicated for each instance.

 They belong to the class rather than any specific instance.

 Static variables can be accessed without creating an object of the class.

 Static variables are declared using the static keyword at the class level.
 Static variables and static blocks are initialized in the order they appear in the code.

 You can access static variables directly through the class name without creating an instance of
the class.

29. What Is the Static Method?


When the static keyword is used, methods can be created that do not require any class instances
to exist. These are known as static methods.

Syntax:
[Access_modifier] static [return_type] methodName([parameters]) {
// Method body
}

30. What Are the Restrictions Applied to the Java


Static Methods?
Here are some of the restrictions on Java static methods:

 Non-Static Access:

 Static methods cannot directly access non-static (instance) members (methods or


variables).

 This restriction exists because static methods operate at the class level, not on specific
instances.

 'this' and 'super' Keywords:

 The this keyword refers to the current instance, which doesn't exist in a static context.

 super refers to the parent class instance, which doesn't apply in a static context.

 Data Access Limitation:

 Static methods can only directly access static data (static variables or other static
methods).
 A static method would need an object reference passed as a parameter to access
instance data.

 No True Overriding:

 Static methods cannot be overridden in subclasses.

 A subclass can define a method with the same signature, but this is method hiding, not
overriding.

31. Why Is the main() Method Static?


It is not possible to invoke a function without constructing an instance of its class, as there is no
object of a class when the JVM starts. The main() function is declared static so that the class can
be loaded by JVM into the main memory. This design allows the Java runtime to begin execution
without instantiating any objects.

 Every Java program begins with the main() function. The main() method is essential because
the compiler begins executing a program from the main() function only.

 The JVM should instantiate the class if the main() function is non-static.

 JVM can simply invoke static methods without generating an instance of the class by utilizing
only the class name.

 The main() function must be declared static, and public, and must have a void return type. The
JVM will be unable to run the Java program and will throw an error if we do not declare it as
static and public or if we do not provide it with a void return type.

32. Can We Override Static Methods?


No, static methods cannot be overridden because method overriding is implemented through
dynamic binding during runtime, whereas static methods are bound through static binding during
compile time. Thus, we cannot override static methods. Often asked, this OOPs interview
question is common.
33. What Is the Static Block?
When we use the static keyword with a block of code, it is referred to as a static block. Unlike
C++, Java supports a special static block (also known as a static clause) for the static
initialization of a class. This code is executed only once when the class is first loaded into
memory.

Here's an example:
public class MyClass {
private static int counter;
private static final double PI;

static {
counter = 0;
PI = calculatePi(); // Assume calculatePi() is a method that computes the value
of pi
System.out.println("Static block executed");
}

// Rest of the class...


}

In this example, the Static block initializes the counter variable to 0 and the PI constant with the
value computed by the calculatePi() method. The message Static block executed will be printed
when the MyClass is loaded into memory.

34. Can a Program Execute Without the Main()


Method?
Yes, a Java program can be executed without a main() method by using a static block.

35. What if the Static Modifier Is Removed From


the Signature of the Main Method?
The removal of the static modifier from the main() method would result in the following problems:
 The program will fail to compile.

 Even if compilation was somehow successful, the Java Virtual Machine could not execute the
program. The JVM looks explicitly for a static main() method as the entry point for any Java
application.

 Without the static modifier, the main would become an instance method. This creates a
paradoxical situation where the JVM would need to create an object of the class to call
the main() method, but it can't create an object without already having a running program.

 The Java language specification explicitly requires the main() method to be static. A non-
static main() method does not conform to these specifications, making the program invalid as
a Java application.

36. What Is the Difference Between Static


Methods and Instance Methods?
This is one of the most commonly asked OOPs interview questions. The following are the
differences between static and instance methods:

 Instance methods have direct access to other instance methods and instance variables.

 Instance methods also have direct access to static variables and static methods.

 Static methods can directly access static variables and static methods.

 Static methods cannot directly access instance methods and instance variables; they must use
an object reference. Furthermore, static methods cannot use this keyword since no instance
exists to reference.

37. What Is this Keyword in Java?


The this keyword in Java is a reference variable that points to the current object within instance
methods or constructors. It's used to distinguish between instance variables and parameters, call
methods or constructors of the current class, and pass the current object as an argument.
38. What Are the Main Uses of this Keyword?
The this keyword has several important uses:

 When instance variables are shadowed by method or constructor parameters, this helps
distinguish them.

 It can be used to call methods of the current class.

 It can be used for constructor chaining within the same class.

 It can be passed as an argument to methods.

 It can be used to return the current class instance from a method.

39. Can We Assign the Reference to this


Variable?
In Java, the this keyword is a reference variable that refers to the current object instance.
However, you cannot assign a new value to this keyword. This restriction is in place
because this keyword is a final reference that always points to the current object, and allowing it
to be reassigned could lead to significant confusion and errors in the code.

40. Can We Use this Keyword to Refer to Static


Members?
In Java, you cannot use this keyword to access static members. The this keyword refers to the
current object instance, whereas static members are class-level entities and not tied to any
particular instance. Therefore, using this in a static context is not allowed.

41. How Can Constructor Chaining Be Done


Using this Keyword?
Constructor chaining using this keyword is a technique where one constructor calls another in
the same class. Here's how it works:

 Use this() call to invoke another constructor.

 The this() call must be the first statement in the constructor.

 Only one this() call can be used per constructor.

Let's illustrate this with an example:

This example shows how constructor chaining is done using this keyword:

 The single-parameter constructor calls the two-parameter constructor.

 The two-parameter constructor calls the three-parameter constructor.

 The three-parameter constructor initializes all fields and sets brand-specific details.

42. Which Class Is the Superclass for All the


Classes?
This is a standard OOPs interview question. The superclass for all classes in Java is the Object
class.

43. Why Is Multiple Inheritance Not Supported in


Java?
Java doesn't support multiple inheritance of classes to avoid the "diamond problem" or "deadly
diamond of death." This problem happens when a class inherits from two classes that have a
common ancestor, leading to potential ambiguity and complexity.

In this scenario, if B and C both override a method from A, which version should D inherit?
This ambiguity can lead to:

 Confusion in method resolution.

 Potential runtime errors.

 Increased complexity in language design and implementation.

 Difficulties in maintaining and understanding the code.

44. What Is Super in Java?


The super keyword in Java is a reference variable that points to the immediate parent class
object.

45. How Can Constructor Chaining Be Done by


Using the Super Keyword?
Constructor chaining using the super keyword can be done to call a constructor in the superclass
from a subclass.

Here's how it works:

 Use the super() call to invoke a constructor in the superclass.

 The super() call must be the first statement in the subclass constructor.

 If not explicitly called, the compiler automatically inserts super() to call the no-argument
constructor of the superclass.

Let's understand this with an example:


// Parent class
class Vehicle {
protected String brand;
protected String model;

public Vehicle() {
this("Unknown", "Unknown");
}
public Vehicle(String brand) {
this(brand, "Unknown");
}

public Vehicle(String brand, String model) {


this.brand = brand;
this.model = model;
}

public void displayInfo() {


System.out.println("Brand: " + brand + ", Model: " + model);
}
}

// Child class
class Car extends Vehicle {
private int numDoors;

public Car() {
super(); // Calls Vehicle()
this.numDoors = 4;
}

public Car(String brand) {


super(brand); // Calls Vehicle(String)
this.numDoors = 4;
}

public Car(String brand, String model) {


super(brand, model); // Calls Vehicle(String, String)
this.numDoors = 4;
}

public Car(String brand, String model, int numDoors) {


super(brand, model); // Calls Vehicle(String, String)
this.numDoors = numDoors;
}

@Override
public void displayInfo() {
super.displayInfo(); // Calls Vehicle's displayInfo()
System.out.println("Number of doors: " + numDoors);
}
}

public class Main {


public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car("Toyota");
Car car3 = new Car("Honda", "Civic");
Car car4 = new Car("Ford", "Mustang", 2);

car1.displayInfo();
car2.displayInfo();
car3.displayInfo();
car4.displayInfo();
}
}

In this example:

 The Vehicle class has three constructors demonstrating constructor chaining within the same
class using this().

 The Car class extends Vehicle and has four constructors:

 The first calls super() to invoke the no-argument constructor of Vehicle.

 The second calls super(brand) to invoke the one-argument constructor of Vehicle.

 The third and fourth call super(brand, model) to invoke the two-argument constructor
of Vehicle.

 Each Car constructor then initializes its own numDoors field.

 The displayInfo() method in Car overrides the one in Vehicle, calling super.displayInfo() to
reuse the parent's implementation before adding its information.

46. What Are the Main Uses of the Super


Keyword?
The super keyword is used for:

 Accessing superclass members

 Invoking superclass constructors

 Invoking superclass methods


47. What Are the Differences Between this and
the Super Keyword?
Following are the differences between this and super keywords:
Aspect this Keyword super Keyword

Refers to the current instance of


Purpose Refers to the immediate parent class instance.
the class.

Usage in Calls another constructor in the Calls a constructor in the immediate parent
Constructors same class. class.

Accessing Accesses members of the current


Accesses members of the parent class.
Members class.

Method Invokes overridden methods of the parent


Invokes current class methods.
Invocation class.

Syntax for
this() or this(parameters) super() or super(parameters)
Constructor Call

Position in
Must be the first statement if used. Must be the first statement if used.
Constructor

Instance methods and Instance methods, constructors, and instance


Applicable to
constructors. variables.

Use with Static Cannot be used with static


Cannot be used with static members.
Members members.

Compiler adds this implicitly Compiler doesn't add super implicitly (except
Implicit Use
when accessing instance members. default for the constructor call).

Used to call the overridden method of the


Overriding Not applicable
parent class

Scope Limited to the current class. Extends to the immediate parent class.

48. Can You Use this() and super() in a


Constructor?
You cannot use this() and super() together in the same constructor.

49. What Is Object Cloning?


Object cloning is the process of creating an exact copy of an object. The clone() method of object
class is used to clone an object. The clone() method provided by the object class in Java is
utilized for this cloning process.

50. Why Is Method Overloading Not Possible by


Changing the Return Type in Java?
This is one of the most commonly asked OOPs interview questions. Method overloading is not
possible by changing only the return type in Java for the following reasons:

 If overloading were allowed based on return type, the compiler wouldn't know which method to
call in situations where the return value is not used.

 Java uses type erasure for generics, which can lead to conflicts if methods differ only by return
type.

 Method overloading is resolved at compile-time based on the method signature, which doesn't
include the return type.

 In Java, a method's signature consists of its name and parameter list, not the return type.

 Allowing overloading by return type would break existing code and Java's commitment to
backward compatibility.

51. What Is Method Overloading With Type


Promotion?
When resolving overloaded methods in Java, if an exact match isn't found, the compiler first
promotes lower data type arguments to higher ones. It checks for a matching method after each
promotion. If a match is found, that method is used.
If not, the compiler continues promoting until all possibilities are exhausted. If no match is found
after all promotions, a compile-time error occurs. This process is known as automatic type
promotion in method overloading.

The promotion follows a hierarchy:

byte → short → int → long → float → double

char → int

Let’s take a practical example of programs based on the automatic type promotion concept:

public class TypePromotionExample {


public void display(int a) {
System.out.println("int: " + a);
}

public void display(double a) {


System.out.println("double: " + a);
}

public static void main(String[] args) {


TypePromotionExample obj = new TypePromotionExample();

byte b = 25;
obj.display(b); // Promotes byte to int

short s = 30;
obj.display(s); // Promotes short to int

char c = 'A';
obj.display(c); // Promotes char to int

float f = 3.14f;
obj.display(f); // Promotes float to double
}
}

In this example:

 The byte and short arguments are promoted to int.

 The char argument is promoted to int.


 The float argument is promoted to double.

52. Can We Change the Scope of the Overridden


Method in the Subclass?
Yes, we can adjust the scope of the overridden method in the subclass. It's important to note that
while increasing its accessibility, we cannot decrease it.

53. What Is the instanceOf Operator?


The instanceof operator is a binary operator that checks whether an object belongs to a specific
type. It returns either true or false, making it a type comparison operator as it matches the
instance against the type. The basic syntax of the instanceof operator is:

The basic syntax of the instanceof operator is:


(object) instanceof (type)

54. What Are the Advantages of Encapsulation in


Java?
Encapsulation in Java, a fundamental concept in real-time programming, provides several
advantages:

 Classes gain complete control over data members and methods This control ensures data
integrity and prevents unintended modifications.

 It simplifies user interaction by concealing complex code implementations This reduces


potential errors and improves user experience.

 It allows class variables to be set as read-only or write-only Tailored to specific needs, this
flexibility protects sensitive data while enabling necessary access.

 Encapsulation facilitates the reuse of existing code Saving time and resources when
developing new applications.
 Updating existing code is easier and less error-prone Crucial for maintaining and scaling
complex software systems.

 Encapsulated code makes unit testing straightforward Leading to more reliable and
maintainable software.

 Popular IDEs support getters and setters Enhancing coding efficiency and developer
productivity.

55. How Many Types of Exceptions Can Occur in


a Java Program?
In Java, exceptions are categorized into three main types:

 Checked exceptions

 Unchecked exceptions (runtime exceptions)

 Errors

56. What Is Exception Handling?


Exception handling is a mechanism designed to manage runtime errors,
including ClassNotFoundException, IOException, SQLException, RemoteException, and others.

57. Explain the Hierarchy of Java Exception


Classes.
In Java's exception hierarchy, the Throwable class occupies the highest position, succeeded by
its subclasses Error and Exception. The following shows the hierarchy of Java Exception
classes.
It's important to differentiate between Error and Exception because they represent fundamentally
different categories of issues, each requiring specific handling approaches.

An exception is an unexpected event in a program that can be managed and recovered from
within the program itself. In contrast, an error represents a more severe condition that typically
cannot be handled within the program as it may cause damage to the system's architecture or
environment.

58. What Is the Difference Between Checked and


Unchecked Exceptions?
Following are the key differences between checked and unchecked exceptions:

Aspect Checked Exceptions Unchecked Exceptions

Compile-Time
Must be caught or declared Not required to be caught or declared
Checking

Subclasses of exception
Class Hierarchy Subclasses of RuntimeException
(excluding RuntimeException )

Error Handling For recoverable errors For programming errors

When to Use Anticipated, recoverable conditions Unexpected failures

Examples IOException, SQLException NullPointerException, ArithmeticException

Method
Must be declared in a throws clause. No need to declare.
Signatures

Propagation Must be explicitly propagated. Automatically propagate.

Performance
Can have some impact. Generally, it has less impact.
Impact

Handling
Enforced by the compiler. Not enforced by the compiler.
Enforcement

59. What Is Finally Block?


The finally block in programming, found commonly in languages such as Java and C#, is a
segment of code that runs regardless of whether an exception is thrown or not.

Typically used with a try-catch block, the finally block ensures critical cleanup operations, like
closing files or database connections, are executed.

Syntax for a finally block:

try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Handle exception of ExceptionType1
} catch (ExceptionType2 e2) {
// Handle exception of ExceptionType2
} finally {
// Code that will always execute, whether an exception occurred or not
}

60. What Is the Difference Between Throw and


Throws?
There are many differences between throw and throws keywords. A list of differences between
them is given below:

Aspect throw throws

Used to explicitly throw an Used to declare that a method might throw


Purpose
exception. exceptions.

Usage Location Used inside a method. Used in the method signature.

At runtime, when a specific At compile time, to inform the caller about


When It's Used
condition is met. possible exceptions.

Number of
Throws a single exception at a time. Can declare multiple exceptions.
Exceptions

Exception Creates and throws an actual Does not create exceptions, it just declares
Creation exception object. possibility.
Immediately transfers control to the
Execution Does not immediately affect program flow.
exception handler.

Handling Not required to be handled or Checked exceptions must be handled or re-


Requirement declared. declared.

Both checked and unchecked


Applicable to Typically used with checked exceptions.
exceptions.

throw new IOException("File not public void readFile() throws IOException,


Example
found"); FileNotFoundException

61. What Is Exception Propagation?


Exception propagation refers to the process of forwarding exceptions from a called method to its
caller. If such an exception isn't handled by the caller, the called method and the caller terminate
execution.

62. What Is Garbage Collection?


Garbage collection is a computer programming term that describes identifying and d eleting
objects no longer referenced by other objects.

In simple terms, garbage collection refers to discarding objects no longer needed or referenced
by any other parts of the program. It's an essential aspect of how JavaScript handles memory
allocation.

63. What Are the Different Types of Garbage


Collectors in Java?
Java provides four types of garbage collectors that can be chosen based on requirements:

 Serial Garbage Collector

 Parallel Garbage Collector

 Concurrent Mark Sweep (CMS) Garbage Collector


 Garbage First (G1) Garbage Collector

64. What Is the Limitation of Garbage Collection?


The main disadvantage of garbage collection is that it pauses all active threads during the
memory recovery phase. Garbage collection algorithms can take significant time, ra nging from
seconds to minutes, to execute. This extended duration makes it challenging to schedule
garbage collection routines predictably.

65. How Can an Object Be Unreferenced?


There are several ways an object can become unreferenced:

 Nulling the Reference: This involves explicitly setting a reference variable to null.

Employee e = new Employee();

e = null; // The Employee object is now unreferenced

 Assigning a Reference to Another: This method reassigns an existing reference to a


different object.

Employee e1 = new Employee();

Employee e2 = new Employee();

e1 = e2; // The first Employee object is now unreferenced

 Anonymous Objects: These are objects created without being assigned to a reference
variable.

new Employee(); // This Employee object is immediately unreferenced

 Objects Going Out of Scope: When a method or block ends, local variables are removed
from the stack.

void createEmployee() {
Employee e = new Employee();

} // 'e' goes out of scope, potentially dereferencing the object

 Removing From Collections: Objects can become unreferenced when removed from
collections.

List<Employee> employees = new ArrayList<>();

employees.add(new Employee());

employees.remove(0); // This Employee object may now be unreferenced

Each of these methods can result in objects becoming unreachable from the root set, making
them eligible for garbage collection. The exact timing of when these objects are collected
depends on the JVM's garbage collection implementation and strategy.

66. What Is the Purpose of the finalize() Method?


The finalize() method is defined in the object class, which can be overridden by subclasses. The
garbage collector calls the finalize() method before an object is collected. This method can
perform essential cleanup tasks before destroying the object, such as releasing resources or
detaching event listeners.

67. What Is the Difference Between Final, Finally,


and Finalize?
Java uses the keywords final, finally, and finalize in its exception handling mechanisms, each
having its specific role. Below is a list of the differences between them:

Aspect final finally finalize

Type keyword block method


To execute code To perform cleanup
To create constants, prevent
Purpose regardless of exception operations before the
inheritance/overriding.
occurrence. object is garbage collected.

Can be applied to variables, Used with try-catch Defined in the object class,
Usage
methods, classes. blocks. can be overridden.

Called by the garbage


When it Compile-time (for variables), Always executes after
collector before reclaiming
Executes runtime (for methods/classes). try-catch blocks.
the object's memory.

Can be No (when applied to


N/A Yes
Overridden methods/classes).

Guaranteed to execute
Execution Not guaranteed to be
N/A (except in specific
Guarantee called.
cases).

Related to Variables, methods, classes Exception handling Object life cycle

Resource cleanup Releasing resources that


Commonly Constants, immutable objects,
(closing files, weren't cleaned up by try-
Used for preventing inheritance.
connections). finally.

You might also like