Top 50 OOPs Interview Questions

Top 50 OOPs Interview Questions

Ques.1. What is OOPs?
Ans. OOPs is abbreviated as Object-Oriented Programming Systems. It’s a computer programming paradigm that is based on objects and classes rather than functions and stored procedures. Object is an instance of a class consisting of properties that makes data useful whereas classes are a representation of an object describing its details and used to organize the data.

Ques.2. Why do we need OOPs?
Ans. There are various reasons for defining the need for OOPs, but the important ones are:-

  • OOps has clarity in programming thus allowing users to solve complex problems easily.
  • OOPs help in increasing the readability, maintainability, and understandability of code.
  • With the help of encapsulation data and code can be bound together thus increasing security.
  • OOPs help in code reusability.
  • OOPs enhance the program modularity as each object exists independently.

Ques.3. What Programming languages use Object-Oriented Programming?
Ans. The programming languages that follow the paradigm of OOPs are:-

  • Java
  • Python
  • Javascript
  • C++
  • PHP
  • Ruby

and many more.

Ques.4. What are the features of OOPs?
Ans. The OOPs comprises of four main features that are:

  • Inheritance – Inheritance is the concept in which one class inherits the property of the other class.
  • Encapsulation – It wraps up the data and the code working together in a single unit.
  • Polymorphism – It’s the ability to exist in multiple forms. It lets users perform a single task in various ways.
  • Data Abstraction – It helps hide the important information from the users and shows only necessary details.

Ques.5. What are the limitations of OOPs?
Ans. The limitations of OOPs are as follows-:

  • Requires a very large amount of time in solving problems as compared to Procedure Oriented Programming.
  • Not suitable for solving small problems.
  • Without the proper class documentation, it is hard to understand the code.
  • Requires a lot of time to solve problems.
  • Programs created with OOPs are way large than that of the same program via a structural programming language.
  • Due to the ample size of programs, it consumes a large amount of memory.

Ques.6. State the differences between OOPs and Structural Programming?
Ans. The following table describes the differences between the OOPs and Structural Programming.

S.No. OOPs Structural Programming
1. OOPs are based on objects and classes rather than functions and stored procedures. Structural Programming is divided into functions and provides a logical structure to the program.
2. Highly Flexible. Less Flexible.
3. Follows Bottom-Up Approach. Follows Top-Down Approach.
4. More secure as data hiding is available. Less secure as data hiding is not available.
5. Can be used to solve complex problems. Can be used to solve moderate problems.

Ques.7. What is a class?
Ans. A class is considered as a blueprint or template using which we can create as many objects as we like. It’s a user-defined function and determines what an object will contain and how it will behave.

For example, A programmer can make three instances of a dog, Pug, Beagle, and Indie. A class will store similar information that is unique to each dog.

Syntax:-

class < class_name > {

field;

method;

}

Ques.8 What is a superclass?
Ans. A superclass exhibits hierarchical relationships with its sub-classes. The superclass acts as a parent or base class and lets the other child classes inherit from it.

For example,

Define a class Vehicle

public class Vehicle {}

A new class created by extending this class

public class Bikes extends Vehicle {}

Ques.9. What is a subclass?
Ans. The subclass is a class that is inherited from the superclass. For example, the Bike is a subclass inherited from the class Vehicle in the above example.

Ques.10. What is an inner class?
Ans. Inner classes are defined in the body of outer classes with curly braces{} enclosing them and have a special relationship with them. Inner classes can be defined in four different ways

  • Inner class
  • Method-local inner class
  • Anonymous inner class
  • Static nested inner class

Ques.11. What is an object?
Ans. An object is an instance of a class and is a real-world entity consisting of behavior, attribute, and properties used to define it. Having characteristic behavior objects consumes space.

For example:-

Object- Fruit

State- Color, shape

Behavior- Taste

Syntax:-

class Fruit {

String color;

String shape;

}

Ques.12. What is a constructor?
Ans. Constructors are used to initialize the objects. The constructors look like a method but it differs from it in the following ways:-

  • A constructor doesn’t return any value.
  • Constructors have the same name as that of a class.
  • Constructor is always called when an object is created.

Syntax:-

MyCollege obj = new MyCollege();

Here, we are calling the default constructor of MyCollege to create a new object.

Ques.13. What is a Destructor?
Ans. In contrast to the constructor, Destructors are also a special method and called automatically whenever an object is destroyed. A destructor has a special name, the same as a class with a tilde sign(~) as a prefix.

For example, the destructor for class String is declared as ~String.

Ques.14. What is constructor overloading?
Ans. Constructor overloading is a concept of defining multiple constructors of the same class in such a way that each constructor performs a different task in the class. However, each constructor must have different input parameters.

For example, three overloaded constructors having different parameter list

public class School{

School(){

….

}

School(String s){

….

}

School(int i){

….

}

….

}

Ques.15. What is coupling in OOPs?
Ans. When an object dependent on any other object is used, it is termed as coupling. It defines how closely two objects are related to each other. There are two types of coupling

  • Loose Coupling – In loose coupling objects are independent of each other. Loose coupling helps in making code flexible and reusable
  • Tight Coupling – In Tight coupling objects are highly interdependent. In this state, it’s hard to modify one code without changing the other code.

Ques.16. What is Inheritance?
Ans. The term Inheritance means the transfer of some quality or behavior from parents to offspring/childs. In OOPs, Inheritance is a process to define a new class based on the structure and behavior defined in some other class. Inheritance increases the reusability of code thus making its implementation simpler.

Ques.17. What are the different types of Inheritance?
Ans. The various types of inheritances are:-

  • Single Inheritance – When a single derived class is inherited from a single base class.
  • Multiple Inheritance – When a derived class inherits from more than one class.
  • Multi-level Inheritance – When a derived class inherits from the other derived class.
  • Hierarchical Inheritance – When more than one derived class is inherited from a single base class.
  • Hybrid Inheritance – Combination of one or more types of inheritances.

Ques.18. What are the limitations of Inheritance?
Ans. The limitations of Inheritance are as-

  • The child and parent class are linked tightly.
  • In case any change in the program is required we need to change parent and child classes.
  • Inherited functions work slower than normal functions.
  • It increases execution time and implementation time.

Ques.19. What is Polymorphism?
Ans. As the word suggests poly means ‘many’ and morph means ‘form’. On the whole, it means ‘one function, multiple forms’. It is one of the most used concepts in OOPs language and is applied to functions or methods. It implements the concept of overriding, virtual function, and overloading.

Ques.20. What are the types of polymorphism? Define them.
Ans. There are two different types of Polymorphism

  • Static or (Compile Time) Polymorphism
  • Dynamic Binding or (Run Time) Polymorphism

Static or (Compile Time) Polymorphism:-

Static Polymorphism occurs at the compile-time and is achieved through method overloading. i.e. Compiler decides what value has to be taken by the body in the picture. There are certain conditions for static polymorphism.

  • The parameters numbers must be different from other parameters.
  • The type of parameter should be different.

Due to different parameters, each method has a different signature.

For example, In the below example the first method takes two parameters and the second method takes three parameters. The compiler looks at the method signature and decides which method to invoke at compile time.

Class StaticPolymorphism

{

int add(int x, int y)

{

return x+y;

}

int add(int x, int y, int z)

{

return x+y+z;

}

}

public class Test

{

public static void main(String args[])

{

StaticPolymorphism obj = StaticPolymorphismr();

System.out.println(obj.add(15, 15));

System.out.println(obj.add(15, 15, 30));

}

}

Output of the Program:-

30

60

Dynamic Binding or (Run-Time) Polymorphism:-

Run time Polymorphism as the name suggests occurs at run time. Method overriding is an example of dynamic polymorphism. There are certain conditions for static polymorphism.

  • With the help of pointers and virtual functions, we can achieve method overriding.
  • When a derived class has the same functions as that of the base class, that base class method is overridden.

For example,

class Car{

void run(){System.out.println(“running”);}

}

class Audi extends Car{

void run(){System.out.println(“running within limits 30km/hr”);}

public static void main(String args[]){

Car b = Audi(); //upcasting

b.run();

}

}

Ques.21. What is Encapsulation?
Ans. In general, encapsulation is used to enclose the data and function together, thus keeping them safe from outside interference. In Encapsulation, the data and code are wrapped up together inside a single unit termed a capsule. Encapsulation is an attribute of an object.

Benefits of Encapsulation-:

  • Data Hiding
  • Flexibility
  • Reusability

Below is an example to make it a bit clear

Pack File:-

package EncapsulationPack;

public class Demo

{

private int variable;

public int getVar()

{

return variable;

}

public void setVar(int v)

{

variable = v;

}

Simple file:

package Encapsulation_Simple;

//import demo_pack.*;

class Normal

{

public static void main(String args[])

{

Sim d=new Pack();

d.setVar(6);

System.out.println(d.getVar());

}

}

Ques.22. What is data abstraction? And how to achieve it?
Ans. Data abstraction is a very important concept in OOPs. It emphasizes the clean separation between the external interface of objects and internal data handling and manipulation. Data abstraction helps in reducing program complexity. There are two ways to achieve data abstraction

  • Abstract Class
  • Abstract Method

You can also read: What is data in a Computer?

Ques.23. What are the different levels of data abstraction?
Ans. Data Abstraction has three levels

  • Physical Level –This is the lowest level of data abstraction and explains how the data is stored in memory. i.e (tells the real location of data stored by the user).
  • Logical Level – This is the middle level of data abstraction. It defines what and how data is stored and structured in the database. It specifies the relationship between data entities in a structured manner.
  • View Level – This level is the highest level of data abstraction. This level defines the user interaction with the database system and a part of the actual database is visible to users. The users can view the data in row and column format although multiple views are also available.

For example,

Let’s say we are storing employee information. i.e emp_id, emp_name, emp_salary etc. At the physical level, these records are defined as a block of storage in memory and are hidden from the programmers. The programmers mostly work at the logical level as the data stored above is represented here as fields and attributes and the logical relationship between the data is visible easily. And at the view level employees are allowed to interact with the help of GUI to enter the various details making them unaware of how these details will be stored.

Ques.24. What are the differences between Abstraction and Encapsulation?
Ans. The differences between Abstraction and Encapsulation are as follows-

S.No. Abstraction Encapsulation
1. Abstraction is used to hide unwanted information. Encapsulation is used to wrap up data and code in a single entity.
2. It works at a design level. It works at the application level.
3. Objects performing abstraction can encapsulate. Objects performing encapsulation are not abstract.
4. Abstraction mainly focuses on outside viewing. Encapsulation mainly focuses on internal viewing.
5. Abstraction can be achieved with the help of class and interfaces. Encapsulation is implemented via class and control is gained with the help of specifiers.

Ques.25. What is the difference between inheritance and polymorphism?
Ans. The difference between inheritance and polymorphism is as follows-

S.No. Inheritance Polymorphism
1. Inheritance is a process to define a new class based on the structure and behavior defined in some other class. Polymorphism can be defined as one function with multiple forms.
2. It is applied to classes. It is applied to functions and methods.
3. Inheritance may be Single, Multiple, Multi-level, Hierarchical and Hybrid. Polymorphism may be of Compile time or Run-time Polymorphism.
4. It supports reusability and code length. Allows the objects to decide the implementation of function at run-time or compile-time.
5. The class ‘bike’ can inherit the feature of the class ‘Vehicles’. The class ‘car’ can also have the function of set_color() and class ‘bike’ can also have the function of set_color() which form of the set_color() is to be implemented at run-time or compile-time.

Ques.26. What are access specifiers?
Ans. Access Specifiers are the special type of reserved keywords used to determine the entities like class, variable, method, and constructor. It is also known as Access Modifiers and helps in the encapsulation process. Access modifiers can be of public, private, and protected types.

Ques.27. What is Method Overloading?
Ans. Method Overloading is a concept in which two or more methods can have the same name with different arguments(signatures). Overloading is related to compile-time polymorphism and can be achieved in three ways…

  • Changing the number of parameters.
  • Changing the data type of parameters.
  • Changing the sequence of the data type of parameters.

For example,

class Overloading

{

static int add_num(int x, int y)

{

return x+y;

}

static double add_num(double x, double y)

{

return x+y;

}

}

class Sum

{

public static void main(String[] args)

{

System.out.println(Sum.add_num(1,2));

System.out.println(Sum.add_num(12.1,12.5));

}

}

Ques.28. What is Method Overriding?
Ans. Method Overriding is a concept of OOPs. It means if a subclass and superclass have the same arguments, then the argument of the subclass overrides the argument/method of the superclass. Method Overriding is related to Run-Time Polymorphism. The method overriding can be done when

  • The arguments of both parent and child are the same.
  • private, static, and final methods cant be overridden.
  • The abstract method of superclass should always be overridden.

For example,

class Vehicle

{

void run()

{

System.out.println(“DRIVEN”);

}

}

//Child class

class SUV extends Vehicle

{

void run()

{

System.out.println(“SUV is DRIVEN”);

}

public static void main(String args[])

{

SUV obj = new SUV();

obj.run();

}

}

Ques.29. What are Tokens? <C/C++>
Ans. Tokens are known as the building block of a program. Tokens are recognized by the compiler and can’t be split into components. Keywords, identifiers, and literals are an example of tokens.

Ques.30. What is an exception?
Ans. An exception is an event that disrupts the normal flow of a program. Exceptions help us in detecting and reacting to unexpected events. The reason for the exception is mainly when the user wants something that is not identified in the program.

For example,

public static void Main()

{

int numerator, denominator;

try

{

int quotient = numerator/denominator;

}

catch (DivideByZeroException e)

{

System.out.println(“Divide By Zero Exception Occurred!”);

}

}

Ques.31. What are different types of exceptions?
Ans. There are two types of exception –

Checked Exception – Checked exceptions are also known as compile-time exceptions as these errors are checked during the compilation of the program. The programmer can handle these errors by making a custom modification to the program. For example, SQLException, ClassNotFoundException, etc.

Example:-

import java.io.*;

class CheckedExceptionExample{

public static void main(String args[]) {

FileInputStream input1 = null;

input1 = new FileInputStream(“D:/file.txt”);

//file.txt does not exist at the location

int m;

while(( m = input1.read() ) != -1) {

System.out.print((char)m);

}

input1.close();

}

}

Output:-

Exception in thread “main” java.lang.Error: Unresolved compilation problems:

Unhandled exception type FileNotFoundException

Unhandled exception type IOException

Unhandled exception type IOException

FileNotFoundException – This is raised when we try to create a new object with a file that doesn’t exist.

IO Exception – It is raised when we try to read() and close() this unknown file.

Unchecked Exception – Unchecked exceptions are also known as run time exceptions as these errors are checked during the run time. The compiler is not responsible for checking these errors. For example, logical errors.

import java.io.*;

class UncheckedExceptionExample{

public static void main(String args[]){

int num[] = {1, 2, 3, 4};

System.out.println(num[5]);

int p = Integer.parseInt (“foo”) ;

int q = 0;

int result = num[1]/q;

System.out.println(result);

}

}

Output:-

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4

Exception in thread “main” java.lang.NumberFormatException: For input string: “foo”

Exception in thread “main” java.lang.ArithmeticException: / by zero

ArrayIndexOutOfBoundsException– This exception is raised because we’re trying to access an element of 5th position in the array of 4 numbers

NumberFormException– This exception arises when we try to put a string to Integer.parseInt().

ArithmeticException– Occurs when an incorrect arithmetic operation is performed.

Ques.32. What are the different keywords used in exceptions?
Ans. Below are the keywords that are used to handle these exceptions are

  • try – Enclose the keyword with a try block so that the exception is handled with the exception handler associated with it.
  • catch – this keyword is preceded by a try block and later catch block can be used.
  • finally – This keyword is used to run the program regardless if the error is handled or not.
  • throw – throw keyword is used to throw an exception.
  • throws – throws keyword is used to declare an exception.

Ques.33. What is meant by exception handling?
Ans. Exception handling is a very important concept that is used to manage and handle errors. These are used to handle run-time errors. Exception handling ensures that the flow of the program doesn’t break during execution.

Ques.34. What are the differences between error and exception?
Ans. The difference between error and exception are as follows-

S.No. Exception Error
1. Can occur at run or compile time. Occurs at run time.
2. Checked and unchecked type. Classified as Unchecked type.
3. Belongs to java.lang.Exception.package. Belongs to java.lang.Error.package.
4. Recovery is possible. Recovery is not possible.

Also, read – Core Java Interview Questions

Ques.35. Differentiate between an abstract class and an interface?
Ans. The difference between abstract class and an interface is-

S.No. Abstract Class Interface
1. Abstract keyword is used to declare abstract class Interface keyword is used to declare interface class
2. Does not supports multiple inheritance Supports multiple inheritance
3. Consists of both abstract and non abstract methods. Consists of both static, default and abstract methods.
4. Abstract classes have final, non-final, static and non-static variables. Interface has only static and final variables.
5. Eg. public abstract class Shape{public abstract void draw();} E.g. public interface Drawable{ void draw(); }

Ques.36. What is meant by Garbage Collection?
Ans. Garbage collection is used to handle the free memory by destroying the unused object and reclaiming the memory. In Java, garbage collection happens automatically till the lifeline of a program.

Ques.37. Do classes consume memory space?
Ans. No, the class does not consume any memory space, it is saved on our hard drive. When we create an object of the class memory allocation takes place.

Ques.38. What do you understand by cohesion? <JAVA>
Ans. Cohesion refers to the degree to which a class is defined to do a specialized specific task instead of multiple tasks. There are two types of cohesion

  • Low Cohesion – When a class is designed to do multiple tasks instead of one specific task it is said to be low cohesive. This approach is termed a Bad Programming Approach as it requires a lot of modifications even for a small code change.
  • High Cohesion – When a class is designed to do one specific task instead of multiple tasks it is said to be highly cohesive. This approach is termed as a Good Programming Approach.

Ques.39. What is constructor chaining? <JAVA>
Ans. In the process of constructor chaining, a sequence of constructors is called upon initialization of the object. It occurs through inheritance. Constructor chaining can be achieved in two ways

  • Within the same class
  • From the parent class

Ques.40. What is the difference between static and dynamic binding? <JAVA>
Ans. Binding refers to the link created between a method call and method binding.

The difference between static and dynamic binding is

S.No. Static Binding Dynamic Binding
1. Uses class and fields for resolution. Uses objects for resolving binding.
2. Method Overloading is an example Method Overriding is an example
3. Methods and variables private, final and static are static bindings. Virtual methods are dynamic binding
4. Gets resolved at compile time. Gets resolved at run time.

You can also check: Statics vs Dynamic Testing

Ques.41. What is ‘this’ pointer?
Ans. This pointer holds the address of the current object. This keyword is used as a differentiator between the current and global objects.

Ques.42. What is the difference between virtual and pure virtual functions?
Ans. The difference between virtual and pure virtual functions are as follows:-

S.No. Virtual Function Pure Virtual Function
1. Virtual function is a part of parent class and can be redefined by subclass. Pure Virtual Functions are declared in Parent class and are derived in subclass.
2. Virtual functions are abstract class. Pure Virtual Functions are not abstract classes.
3. Parent classes containing the Virtual Function can be instantiated. Parent classes containing the Pure Virtual Function can’t be instantiated as they become abstract classes.
4. Syntaxvirtual(){// code} Syntaxvirtual() = 0;
5. Definition is given in base class. No Definition is given in base class.

Ques.43. What is the difference between overriding and shadowing?
Ans. The key differences between overriding and shadowing are as-

S.No. Overriding Shadowing
1. It redefines the implementation of a method. It redefines the complete method.
2. Parent class can be accessed via child class. Parent class cannot be accessed with the child class.
3. Keyword Overridable or Mustoveride is required in the base class. Keyword shadow is recommended in the base class.
4. Only a procedure or property can be redefined. Any declared element can be redefined.
5. Can not change readability and writability of overridden element Can change readability and writability of redefined element

Ques.44. What is the difference between structure and class?
Ans.

S.No. Structure Class
1. Structure is a collection of data types combined logically. Class is a set of instructions that is used to specify objects.
2. Structure is Public. Class is Private.
3. Structure does not support Inheritance. Class supports Inheritance.
4. Structures are used in small programs. Classes are used in large programs.
5. Syntaxclass class_name{data member;member function;} Syntaxstruct structure_name{type struct_element 1;type struct_element 2;}

Ques.45. What is a friend function?
Ans. A friend function of class has access to private and protected members of other class. A friend function is declared globally outside the scope of class.

Syntax:-

class className {

… .. …

friend returnType functionName(arguments);

… .. …

}

By using the friend function, the compiler understands that the function given is a friend function.

Ques.46. What is Enum in JAVA?
Ans. “Enum” is a short form of “Enumerators”. Enum is a class that represents a group of constants(unchangeable variables). It is declared with the word using Enum and helps in bridging the gap between numbers and objects.

For example,

enum Tiers{

Low,

Medium,

High

}

Level myVar = Level.Medium;

Ques.47. What is a Delegate?
Ans. A delegate is an object-oriented type-safe function pointer. It holds the reference to a function in the .NET framework. It is similar to the function pointer in C or C++. The delegate signature includes the delegate of the function that it points i.e. name, return and arguments passed to it

There are two types of delegates

  • Single Cast – Points to a single method
  • Multi-Cast – Points to multiple methods with the same signature.

Ques.48. What is Operator Overloading?
Ans. Operator Overloading is a user-defined mechanism to give the operators a special meaning. With the help of Operator overloading, we can perform different operations using one operator.

Syntax:-

class Class_name

{

public

return_type operator symbol (argument(s))

{

//code

}

};

Ques.49. What are the operators that cant be overloaded (C++)?
Ans. The operators that cant be overloaded are-

  • Scope Resolution Operator “::”
  • Pointer to Member Operator “.*”
  • Dot or Member access Operator “.”
  • Ternary Operators “?:”

Ques.50. Is Operator Overloading Supported in JAVA?
Ans. No, Operator Overloading is NOT supported in JAVA due to the following reasons

  • Makes code complex
  • Programming Error
  • Easy to develop tools like IDEs

От QA genius

Adblock
detector