OOP Interview Questions


1. What is Object Oriented Programming?

OOP is a technique to develop modules. These modules are assembled together as software.

OOP works on the objects. Everything in OOP is object. Object is made up of states and behaviors.

Objects communicate with each other by sending messages to each other. Object hierarchy are built using Aggregation and Composition.

2. What is Cohesion?

In OOP we develop our code in modules. Each module has certain responsibilities. Cohesion shows how much a module responsibilities are strongly related. 

Higher cohesion is always preferred. Higher cohesion benefits are:
- Improves maintenance of modules.
- Increase re-usability.

3. What is Coupling?

OOP Modules are dependent on each other. Coupling refers to level of dependency between two software modules.

Two modules are highly dependent on each other if you have changed in one module and for supporting that change every time you have to change in dependent module.

Loose Coupling is always preferred.

Inversion of Control and dependency injections are some techniques for getting loose coupling in modules.

4. What is Abstraction?

Abstraction is a technique of taking something specific and making it less specific. 

In OOP we achieve the abstraction by separating the implementation from interface. We take a implemented class and took only those method signatures and properties which are required by the class client. We put these method signatures and properties into interface or abstract class.

5. What is Encapsulation?

In non object oriented languages, data and behaviors are not tied together. That means any function in the program can modify the data.

In Encapsulation, we bind the data and behaviors in one object. Only defined behaviors in a class can modify the data. We hide the state of an object by using properties and methods. Clients of the object only see these behaviors and by only these behaviors clients can modify the data.

We also protect the data by using access specifiers. We put the private / protected keywords before data to protect it from the outside world.

6. What is Polymorphism?

Polymorphism is the ability of a Subtype to be treated as if it were an instance of the Supertype. Any method that accepts an instance of Supertype will also be able to accept an instance of Subtype without any casting required by the client side.

This allows multiple object of different subtypes to be treated as object of single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to.

There are mainly two advantages of polymorphism:

We don't need to deal with family of types. We just need to specify the Supertype and we can assign any Subtype.
We can later add multiple Subtypes that increase the extensibility of the program.

7. What is Inheritance?

Inheritance is the ability to define a new class that inherits the behaviors of an existing class. The new class is a called Supertype and the original class is a Subtype.

Inheritance denotes a "is-a" relationship between classes.

8. What is difference between Abstract class and Interface (Abstract vs Interface)?

InterfaceAbstract Class
All members are abstract.Some members are abstract some are fully implemented.
We can only define some members like events, properties, indexers and methods in an interface.We can define any member in Abstract class.
Interfaces supports multiple inheritance.Abstract class does not support multiple inheritance.
Interfaces are generic in nature. They can be implemented by any class for e.g. IClone interface can be implemented by any class like business objects, Database classes.Abstract classes are related. For e.g. ViewModelBase is an abstract class, then we knows this class will only inherits by ViewModels.

9. What is difference between Composition and Aggregation (Composition vs Aggregation)?

Association is a relationship between two objects. This relationship may be one-o-one, one-to-many, many-to-one, and many-to-many.

For e.g. a student and teacher objects have an association.

Aggregation is a special case of association in which objects have a "has-a" relationship. 

Composition is also a "has-a" relationship but It is a special case of Aggregation in which an object manages the life cycle of another object.

For example, a library contains students and books. Relationship between library and students is Aggregation. Relationship between library and books is composition. A student can exist without a library and therefore it is aggregation. A book cannot exists without a library and therefore it is composition.

10. What is Is-A and Has-A relationship?

An inheritance relationship is an "is-a" relationship. A composition relationship is a "has-a" relationship.


1. Write basic concepts of OOPS?

Abstraction.
Encapsulation.
Inheritance.
Polymorphism.

2. What is a class?

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describes the details of an object.

3. What is an object?

An object for constructor as an instance of a class, and it has its own state, behavior, and identity.

4. Difference between class and an object?

An object is an instance of a class. Objects hold multiple information, but classes don’t have any information. Definition of properties and functions can be done at class and can be used by the object.

5. What is constructor?

A constructor is a method used to initialize the state of an object, and it gets invoked at the time of object creation. Rules for constructor are:

Constructor Name should be same as class name.
A constructor must have no return type.

6. Do we require a parameter for constructors?

No, we do not require a parameter for constructors.

7. What is a copy constructor?

This is a special constructor for creating a new object as a copy of an existing object.

8. What is Destructor?

A destructor is a method which is automatically called when the object is made of scope or destroyed. Destructor name is also same as class name but with the tilde symbol before the name.

9. What is the use of finalize method?

Finalize method helps to perform cleanup operations on the resources which are not currently used. Finalize method is protected, and it is accessible only through this class or by a derived class.

10. What is a virtual function?

A virtual function is a member function of class, and its functionality can be overridden in its derived class. This function can be implemented by using a keyword called virtual, and it can be given during function declaration.

11. What is function overloading?

Function overloading an as a normal function, but it can perform different tasks. It allows the creation of several methods with the same name which differ from each other by the type of input and output of the function.

12. What is operator overloading?

Operator overloading is a function where different operators are applied and depends on the arguments. Operator,-,* can be used to pass through the function, and it has their own precedence to execute

13. What is method overriding?

Method overriding is a feature that allows a subclass to provide the implementation of a method that overrides in the main class. This will overrides the implementation in the superclass by providing the same method name, same parameter and same return type.

14. Difference between overloading and overriding?

Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the same method with different arguments, and it may or may not return the same value in the same class itself.

Overriding is the same method names with same arguments and return types associated with the class and its child class.

15. What is an abstract class?

An abstract class is a class which cannot be instantiated. Creation of an object is not possible with an abstract class, but it can be inherited. An abstract class can contain only Abstract method. Java allows only abstract method in abstract class while for other languages allow non-abstract method as well.

16. What is an interface?

An interface is a collection of an abstract method. If the class implements an inheritance, and then thereby inherits all the abstract methods of an interface.

17. What is a ternary operator?

The ternary operator is said to be an operator which takes three arguments. Arguments and results are of different data types, and it depends on the function. The ternary operator is also called a conditional operator.

18. What are different types of arguments?

A parameter is a variable used during the declaration of the function or subroutine and arguments are passed to the an, and it should match with the parameter defined. There are two types of Arguments.

Call by Value – Value passed will get modified only inside the function, and it returns the same value whatever it is passed it into the function.
Call by Reference – Value passed will get modified in both inside and outside the functions and it returns the same or different value.

19.  What is exception handling?

An exception is an event that occurs during the execution of a program. Exceptions can be of any type – Runtime exception, Error exceptions. Those exceptions are adequately handled through exception handling mechanism like try, catch and throw keywords.

20. What are access modifiers?

Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are 3 types of access modifiers, and they are as follows:

Private.
Protected.
Public.

21. What are sealed modifiers?

Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers can also be applied to properties, events, and methods. This modifier cannot be applied to static members.

22. What is the default access modifier in a class?

The default access modifier of a class is Private by default.

23. How can we call the base method without creating an instance?

Yes, it is possible to call the base method without creating an instance. And that method should be “Static method”.

Doing inheritance from that class.-Use Base Keyword from a derived class.

24. What is the difference between new and override?

The new modifier instructs the compiler to use the new implementation instead of the base class function. Whereas, Override modifier helps to override the base class function.

25. What is early and late binding?

Early binding refers to the assignment of values to variables during design time whereas late binding refers to the assignment of values to variables during run time.

26. What is ‘this’ pointer?

THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which differentiates between the current object with the global object. Basically, it refers to the current object.

27. What is the difference between structure and a class?

Structure default access type is public , but class access type is private. A structure is used for grouping data whereas class can be used for grouping data and methods. Structures are exclusively used for data, and it doesn’t require strict validation , but classes are used to encapsulates and inherit data which requires strict validation.

28. What is dynamic or run time polymorphism?

Dynamic or Run time polymorphism is also known as method overriding in which call to an overridden function is resolved during run time, not at the compile time. It means having two or more methods with the same name, same signature but with different implementation.

29. What does the keyword virtual represented in the method definition?

It means, we can override the method.

30. Whether static method can use nonstatic members?

False.

31. What is static and dynamic binding?

Binding is nothing but the association of a name with the class. Static binding is a binding in which name can be associated with the class during compilation time, and it is also called as early Binding.

Dynamic binding is a binding in which name can be associated with the class during execution time, and it is also called as Late Binding.

32. How many instances can be created for an abstract class?

Zero instances will be created for an abstract class.

33. Which OOPS concept is used as reuse mechanism?

Inheritance is the OOPS concept that can be used as reuse mechanism.

34. Which OOPS concept exposes only necessary information to the calling functions?

Encapsulation


1. What is object-oriented programming (OOP)?

OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object is created in the program to represent a class. Therefore, an object encapsulates all the features, such as data and behavior that are associated to a class. OOP allows developers to develop modular programs and assemble them as software. Objects are used to access data and behaviors of different software modules, such as classes, namespaces, and sharable assemblies. .NET Framework supports only OOP languages, such as Visual Basic .NET, Visual C#, and Visual C++.

2. What is a class?

A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type, which represents a blue print of objects. It is a template of object.

A class can be defined as the primary building block of OOP. It also serves as a template that describes the properties, state, and behaviors common to a particular group of objects.

A class contains data and behavior of an entity. For example, the aircraft class can contain data, such as model number, category, and color and behavior, such as duration of flight, speed, and number of passengers. A class inherits the data members and behaviors of other classes by extending from them.

3. What is an object?

They are instance of classes. It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Attributes and behavior of an object are defined by the class definition.

4. What is the relationship between a class and an object?

A class acts as a blue-print that defines the properties, states, and behaviors that are common to a number of objects. An object is an instance of the class. For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle, such as Van, Truck, and Auto.

The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.

5. Explain the basic features of OOPs.

The following are the four basic features of OOP:
Abstraction - Refers to the process of exposing only the relevant and essential data to the users without showing unnecessary information.
Polymorphism - Allows you to use an entity in multiple forms.
Encapsulation - Prevents the data from unwanted access by binding of code and data in a single unit called object.
Inheritance - Promotes the reusability of code and eliminates the use of redundant code. It is the property through which a child class obtains all the features defined in its parent class. When a class inherits the common properties of another class, the class inheriting the properties is called a derived class and the class that allows inheritance of its common properties is called a base class.

6. How can you prevent your class to be inherited further?

You can prevent a class from being inherited further by defining it with the sealed keyword.

7. Can you specify the accessibility modifier for methods inside the interface?

All the methods inside an interface are always public, by default. You cannot specify any other access modifier for them.

8. Is it possible for a class to inherit the constructor of its base class?

No, a class cannot inherit the constructor of its base class.

9. How is method overriding different from method overloading?

Overriding involves the creation of two or more methods with the same name and same signature in different classes (one of them should be parent class and other should be child).

Overloading is a concept of using a method at different places with same name and different signatures within the same class.

10. What is the difference between a class and a structure?

Class:
A class is a reference type.
While instantiating a class, CLR allocates memory for its instance in heap.
Classes support inheritance.
Variables of a class can be assigned as null.
Class can contain constructor/destructor.

Structure:
A structure is a value type.
In structure, memory is allocated on stack.
Structures do not support inheritance.
Structure members cannot have null values.
Structure does not require constructor/destructor and members can be initialiazed automatically.

11. What are similarities between a class and a structure.

Structures and classes are the two most important data structures that are used by programmers to build modular programs by using OOP languages, such as Visual Basic .NET, and Visual C#. The following are some of the similarities between a class and a structure:
Access specifiers, such as public, private, and protected, are identically used in structures and classes to restrict the access of their data and methods outside their body.
The access level for class members and struct members, including nested classes and structs, is private by default. Private nested types are not accessible from outside the containing type.
Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
Both structures and classes can implement interfaces to use multiple-inheritance in code.
Both structures and classes can have constructors with parameter.
Both structures and classes can have delegates and events.

12. Can you declare an overridden method to be static if the original method is not static?

No. Two virtual methods must have the same signature.

13. Why is the virtual keyword used in code?

The virtual keyword is used while defining a class to specify that the methods and the properties of that class can be overridden in derived classes.

14. Can you allow a class to be inherited, but prevent a method from being overridden in C#?

Yes. Just declare the class public and make the method sealed.

15. Is it a good practice to handle exceptions in code?

Yes, you must handle exceptions in code so that you can deal with any unexpected situations that occur when a program is running. For example, dividing a number by zero or passing a string value to a variable that holds an integer value would result in an exception.

16. Explain the concept of constructor?

Constructor is a special method of a class, which is called automatically when the instance of a class is created. It is created with the same name as the class and initializes all class members, whenever you access the class. The main features of a constructor are as follows:
Constructors do not have any return type.
Constructors can be overloaded.
It is not mandatory to declare a constructor; it is invoked automatically by .NET Framework.

17. Can you inherit private members of a class?

No, you cannot inherit private members of a class because private members are accessible only to that class and not outside that class.

18. Does .NET support multiple inheritance?

.NET does not support multiple inheritance directly because in .NET, a class cannot inherit from more than one class. .NET supports multiple inheritance through interfaces.

19. What is the syntax to inherit from a class in C#?

When a class is derived from another class, then the members of the base class become the members of the derived class. The access modifier used while accessing members of the base class specifies the access status of the base class members inside the derived class.

The syntax to inherit a class from another class in C# is as follows:
class MyNewClass : MyBaseclass

20. State the features of an interface.

An interface is a template that contains only the signature of methods. The signature of a method consists of the numbers of parameters, the type of parameter (value, reference, or output), and the order of parameters. An interface has no implementation on its own because it contains only the definition of methods without any method body. An interface is defined using the interface keyword. Moreover, you cannot instantiate an interface. The various features of an interface are as follows:
An interface is used to implement multiple inheritance in code. This feature of an interface is quite different from that of abstract classes because a class cannot derive the features of more than one class but can easily implement multiple interfaces.
It defines a specific set of methods and their arguments.
Variables in interface must be declared as public, static, and final while methods must be public and abstract.
A class implementing an interface must implement all of its methods.
An interface can derive from more than one interface.

21. What are methods?

Methods are the building blocks of a class, in which they are linked together to share and process data to produce the result. In other words, a method is a block of code that contains a series of statements and represents the behavior of a class. While declaring a method you need to specify the access specifier, the return value, the name of the method, and the method parameters. All these combined together is called the signature of the method.

22. What is a namespace?

Namespace is considered as a container that contains functionally related group of classes and other types.

23. Do events have return type?

No, events do not have return type.

24. What is the function of the Try-Catch-Finally block?

The try block encloses those statements that can cause exception and the catch block handles the exception, if it occurs. Catch block contains the statements that have to be executed, when an exception occurs. The finally block always executes, irrespective of the fact whether or not an exception has occurred. The finally block is generally used to perform the cleanup process. If any exception occurs in the try block, the program control directly transfers to its corresponding catch block and later to the finally block. If no exception occurs inside the try block, then the program control transfers directly to the finally block.

25. How can you prevent a class from overriding in C#?

You can prevent a class from overriding in C# by using the sealed keyword.

26. What are abstract classes? What are the distinct characteristics of an abstract class?

An abstract class is a class that cannot be instantiated and is always used as a base class.
The following are the characteristics of an abstract class:
You cannot instantiate an abstract class directly. This implies that you cannot create an object of the abstract class; it must be inherited.
You can have abstract as well as non-abstract members in an abstract class.
You must declare at least one abstract method in the abstract class.
An abstract class is always public.
An abstract class is declared using the abstract keyword.

The basic purpose of an abstract class is to provide a common definition of the base class that multiple derived classes can share.

27. Give a brief description of properties in C# and the advantages that are obtained by using them in programs.

In C#, a property is a way to expose an internal data element of a class in a simple and intuitive manner. In other words, it is a simple extension of data fields. You can create a property by defining an externally available name and then writing the set and get property accessors. The get property accessor is used to return the property value. The set property accessor is used to assign a new value to the property.

28. Explain different types of inheritance.

Inheritance in OOP is of four types:
Single inheritance - Contains one base class and one derived class
Hierarchical inheritance - Contains one base class and multiple derived classes of the same base class
Multilevel inheritance - Contains a class derived from a derived class
Multiple inheritance - Contains several base classes and a derived class
All .NET languages supports single, hierarchical, and multilevel inheritance. They do not support multiple inheritance because in these languages, a derived class cannot have more than one base class. However, you can implement multiple inheritance in.NET through interfaces.

29. You have defined a destructor in a class that you have developed by using the C# programming language, but the destructor never executed. Why did the destructor not execute?

The runtime environment automatically invokes the destructor of a class to release the resources that are occupied by variables and methods of an object. However, in C#, programmers cannot control the timing for invoking destructors, as Garbage Collector is only responsible for releasing the resources used by an object. Garbage Collector automatically gets information about unreferenced objects from .NET's runtime environment and then invokes the Finalize() method.

Although, it is not preferable to force Garbage Collector to perform garbage collection and retrieve all inaccessible memory, programmers can use the Collect() method of the Garbage Collector class to forcefully execute Garbage Collector.

30. Can users define their own exceptions in code?

Yes, customized exceptions can be defined in code by deriving from the System.Exception class.

31. Is it possible to execute two catch blocks?

You are allowed to include more than one catch block in your program; however, it is not possible to execute them in one go. Whenever, an exception occurs in your program, the correct catch block is executed and the control goes to the finally block.

32. What do you mean by data encapsulation?

Data encapsulation is a concept of binding data and code in single unit called object and hiding all the implementation details of a class from the user. It prevents unauthorized access of data and restricts the user to use the necessary data only.

33. What is the difference between procedural and object-oriented programming?

Procedural programming is based upon the modular approach in which the larger programs are broken into procedures. Each procedure is a set of instructions that are executed one after another. On the other hand, OOP is based upon objects. An object consists of various elements, such as methods and variables.

Access modifiers are not used in procedural programming, which implies that the entire data can be accessed freely anywhere in the program. In OOP, you can specify the scope of a particular data by using access modifiers - public, private, internal, protected, and protected internal.

34. Explain the concept of destructor?

A destructor is a special method for a class and is invoked automatically when an object is finally destroyed. The name of the destructor is also same as that of the class but is followed by a prefix tilde (~).

A destructor is used to free the dynamic allocated memory and release the resources. You can, however, implement a custom method that allows you to control object destruction by calling the destructor.

The main features of a destructor are as follows:
Destructors do not have any return type
Similar to constructors, destructors are also always public
Destructors cannot be overloaded.

35. Can you declare a private class in a namespace?

The classes in a namespace are internal, by default. However, you can explicitly declare them as public only and not as private, protected, or protected internal. The nested classes can be declared as private, protected, or protected internal.

36. A structure in C# can implement one or more interfaces. Is it true or false?

Yes, it is true. Like classes, in C#, structures can implement one or more interfaces.

37. What is a static constructor?
Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created.

The static constructor has the following features:
No access specifier is required to define it.
You cannot pass parameters in static constructor.
A class can have only one static constructor.
It can access only static members of the class.
It is invoked only once, when the program execution begins.

38. What are the different ways a method can be overloaded?

The different ways to overload a method are given as follows:
By changing the number of parameters used
By changing the order of parameters
By using different data types for the parameters

39. Differentiate between an abstract class and an interface.

Abstract Class:
A class can extend only one abstract class
The members of abstract class can be private as well as protected.
Abstract classes should have subclasses
Any class can extend an abstract class.
Methods in abstract class can be abstract as well as concrete.
There can be a constructor for abstract class.
The class extending the abstract class may or may not implement any of its method.
An abstract class can implement methods.

Interface:
A class can implement several interfaces
An interface can only have public members.
Interfaces must have implementations by classes
Only an interface can extend another interface.
All methods in an interface should be abstract
Interface does not have constructor.
All methods of interface need to be implemented by a class implementing that interface.
Interfaces cannot contain body of any of its method.

40. What are structures?

Structure is a heterogeneous collection of elements referenced by the same name. A structure is declared using the struct keyword. The following is an example that creates a structure to store an employee's information:
struct emp
{
 fixed int empID[15];
 fixed char name[30];
 fixed char addr[50];
 fixed char dept[15];
 fixed char desig[15];
}
The preceding example defines a structure emp and the members of this structure specify the information of an employee.

41. When do you really need to create an abstract class?

We define abstract classes when we define a template that needs to be followed by all the derived classes.

Không có nhận xét nào :

Đăng nhận xét