Interview questions and answers on Object-Oriented Programming (OOP) in C#
Here are 21 interview questions and answers on Object-Oriented Programming (OOP) in C#, along with detailed explanations and code examples:
What is Object-Oriented Programming? Answer: Object-Oriented Programming is a programming paradigm that organizes code around objects, which are instances of classes. It emphasizes concepts like encapsulation, inheritance, and polymorphism.
What is a class? Answer: A class is a blueprint or template that defines the characteristics and behavior of an object. It encapsulates data (attributes) and methods (functions) that operate on that data.
C#class MyClass { // Attributes public int MyAttribute { get; set; } // Methods public void MyMethod() { // Code goes here } }
What is an object? Answer: An object is an instance of a class. It represents a particular entity in memory that has its own set of attributes and can perform operations defined by the class.
C#MyClass myObject = new MyClass(); myObject.MyAttribute = 10; myObject.MyMethod();
What is encapsulation? Answer: Encapsulation is the concept of bundling data (attributes) and methods (functions) together within a class. It hides the internal details and provides access to them through methods or properties, ensuring data integrity and protecting it from external manipulation.
What is inheritance? Answer: Inheritance is a mechanism where one class (derived class) acquires the properties and behaviors of another class (base class). It allows code reusability and supports the "is-a" relationship.
C#class MyBaseClass { // Base class members } class MyDerivedClass : MyBaseClass { // Derived class members }
What is polymorphism? Answer: Polymorphism is the ability of an object to take on different forms or behaviors. It allows objects of different classes to be treated as objects of a common base class, enabling method overriding and method overloading.
What is method overloading? Answer: Method overloading is the ability to define multiple methods with the same name but different parameter lists. The compiler resolves which method to call based on the number, type, and order of the arguments.
C#class MyMath { public int Add(int a, int b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } }
What is method overriding? Answer: Method overriding is the ability to provide a different implementation of a method in a derived class compared to its base class. It is achieved by using the
override
keyword and maintaining the same method signature.C#class MyBaseClass { public virtual void MyMethod() { // Base class implementation } } class MyDerivedClass : MyBaseClass { public override void MyMethod() { // Derived class implementation } }
What is an abstract class? Answer: An abstract class is a class that cannot be instantiated directly. It serves as a base class for other classes and can contain abstract methods (without implementation) and non-abstract methods.
C#abstract class MyAbstractClass { public abstract void MyAbstractMethod(); public void MyMethod() { // Code goes here } }
What is an interface? Answer: An interface is a contract that defines a set of methods and properties that a class must implement. It provides a way to achieve multiple inheritance and promotes loose coupling between classes.
C#interface IMyInterface { void MyMethod(); } class MyClass : IMyInterface { public void MyMethod() { // Interface method implementation } }
What is a constructor? Answer: A constructor is a special method that is called when an object is created. It initializes the object's state and is used to allocate memory and set default values for the object's attributes.
C#class MyClass { public MyClass() { // Constructor code } }
What is a destructor? Answer: A destructor is a special method called when an object is destroyed or garbage collected. It is used to release any resources held by the object, such as closing files or database connections.
C#class MyClass { ~MyClass() { // Destructor code } }
What is a static class? Answer: A static class is a class that cannot be instantiated and can only contain static members (methods, properties, fields). It provides a convenient way to group related utility methods and is accessed using the class name.
C#static class MyUtilityClass { public static void MyMethod() { // Code goes here } }
What are access modifiers? Answer: Access modifiers control the visibility and accessibility of classes, members, and types. The four main access modifiers in C# are
public
,private
,protected
, andinternal
.public
: The member is accessible from any code.private
: The member is accessible only within the containing class.protected
: The member is accessible within the containing class and its derived classes.internal
: The member is accessible within the same assembly (project).
What is a property? Answer: A property is a member of a class that provides a way to encapsulate and control access to its private fields. It consists of a get accessor and an optional set accessor.
C#class MyClass { private int myField; public int MyProperty { get { return myField; } set { myField = value; } } }
What is method hiding? Answer: Method hiding is a concept where a derived class defines a method with the same name as a method in the base class, but it is not an override. It is achieved by using the
new
keyword.C#class MyBaseClass { public void MyMethod() { Console.WriteLine("Base class method"); } } class MyDerivedClass : MyBaseClass { public new void MyMethod() { Console.WriteLine("Derived class method"); } }
What is the difference between
struct
andclass
? Answer: In C#, astruct
is a value type that is stored on the stack, while aclass
is a reference type that is stored on the heap. Additionally,structs
are copied by value, whereasclasses
are copied by reference.What is the difference between
sealed
andstatic
? Answer: Thesealed
modifier is used to prevent a class from being inherited, while thestatic
modifier is used to declare members that belong to the class itself rather than individual objects.What is the difference between an abstract class and an interface? Answer: An abstract class can have both method definitions and implementations, while an interface can only have method signatures. A class can inherit from only one abstract class, but it can implement multiple interfaces.
What is the difference between method overriding and method overloading? Answer: Method overriding involves providing a different implementation of a method in a derived class, whereas method overloading involves defining multiple methods with the same name but different parameters within a single class.
What is the
base
keyword used for? Answer: Thebase
keyword is used to access members (methods, properties, fields) of the base class from within a derived class. It is helpful when a derived class wants to extend or override the base class's functionality.
These questions cover the fundamental concepts of object-oriented programming in C#. Make sure to study and understand the concepts thoroughly, as they are essential for C# development.
C#// Bank class representing a bank entity
class Bank
{
private List<Customer> customers;
public Bank()
{
customers = new List<Customer>();
}
public void AddCustomer(Customer customer)
{
customers.Add(customer);
}
// Polymorphism: Override ToString() method to provide custom string representation of the object
public override string ToString()
{
return "Bank";
}
}
// Customer class representing a bank customer
class Customer
{
private string name;
private List<Account> accounts;
public Customer(string name)
{
this.name = name;
accounts = new List<Account>();
}
public void AddAccount(Account account)
{
accounts.Add(account);
}
// Encapsulation: Get customer name through a property
public string Name
{
get { return name; }
}
}
// Account class representing a bank account
class Account
{
private int accountNumber;
private decimal balance;
// Constructor: Initialize account with an account number and initial balance
public Account(int accountNumber, decimal initialBalance)
{
this.accountNumber = accountNumber;
balance = initialBalance;
}
// Encapsulation: Get account balance through a property
public decimal Balance
{
get { return balance; }
}
// Encapsulation: Perform deposit operation
public void Deposit(decimal amount)
{
balance += amount;
}
// Encapsulation: Perform withdrawal operation
public void Withdraw(decimal amount)
{
balance -= amount;
}
}
// Transaction class representing a bank transaction
class Transaction
{
private Account fromAccount;
private Account toAccount;
private decimal amount;
public Transaction(Account fromAccount, Account toAccount, decimal amount)
{
this.fromAccount = fromAccount;
this.toAccount = toAccount;
this.amount = amount;
}
// Inheritance: Override ToString() method to provide custom string representation of the object
public override string ToString()
{
return $"Transaction: {amount} transferred from Account {fromAccount} to Account {toAccount}";
}
}
Now, let's demonstrate the usage of these classes in a simple scenario:
c#class Program
{
static void Main()
{
Bank myBank = new Bank();
// Create customers
Customer customer1 = new Customer("John Doe");
Customer customer2 = new Customer("Jane Smith");
// Add customers to the bank
myBank.AddCustomer(customer1);
myBank.AddCustomer(customer2);
// Create accounts for customers
Account account1 = new Account(1001, 1000);
Account account2 = new Account(2001, 500);
// Associate accounts with customers
customer1.AddAccount(account1);
customer2.AddAccount(account2);
// Perform transactions
Transaction transaction1 = new Transaction(account1, account2, 200);
Transaction transaction2 = new Transaction(account2, account1, 100);
account1.Withdraw(200);
account2.Deposit(200);
// Output the bank's customers and their account balances
foreach (Customer customer in myBank.Customers)
{
Console.WriteLine($"Customer: {customer.Name}");
foreach (Account account in customer.Accounts)
{
Console.WriteLine($"Account Number: {account.AccountNumber}, Balance: {account.Balance}");
}
}
// Output the transactions
Console.WriteLine(transaction1);
Console.WriteLine(transaction2);
}
}
In this example, we have demonstrated the following OOP concepts:
- Class: We have defined classes for Bank, Customer, Account, and Transaction.
- Object: We have created instances of these classes, such as
myBank
,customer1
,account1
, etc. - Encapsulation: We have encapsulated data within classes using private fields and exposed access to them through properties.
- Inheritance: We have created a base class
Account
and derived classes could be created if needed. - Polymorphism: We have overridden the
ToString()
method in theBank
andTransaction
classes to provide custom string representations. - Constructor: We have used constructors to initialize objects with initial values.
- Method: We have defined methods within classes, such as
Deposit()
andWithdraw()
in theAccount
class. - Access Modifiers: We have used access modifiers (
private
andpublic
) to control the visibility and accessibility of class members. - Association: We have associated accounts with customers by maintaining a list of accounts within the
Customer
class. - Composition: We have composed customers within the
Bank
class and accounts within theCustomer
class. - Object Interaction: We have demonstrated interactions between objects, such as performing transactions between accounts.
This example showcases how different OOP concepts can be applied to model a real-world scenario.
0 Comments