Explain different t...
Explain different t...
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a new class to inherit properties and methods from an existing class. This promotes code reusability and establishes a parent-child relationship between classes. In .NET Core, as in other OOP languages, there are several types of inheritance:
Single inheritance is when a class inherits from only one base class. This is the most straightforward and common form of inheritance. In .NET Core, this is achieved using the :
symbol.
class Animal {
public void Eat() {
Console.WriteLine("Animal is eating.");
}
}
class Dog : Animal {
public void Bark() {
Console.WriteLine("Dog is barking.");
}
}
Multilevel inheritance occurs when a class is derived from another derived class, forming a chain of inheritance.
class Animal {
public void Eat() {
Console.WriteLine("Animal is eating.");
}
}
class Mammal : Animal {
public void Run() {
Console.WriteLine("Mammal is running.");
}
}
class Dog : Mammal {
public void Bark() {
Console.WriteLine("Dog is barking.");
}
}
Hierarchical inheritance is when multiple classes inherit from a single base class.
class Animal {
public void Eat() {
Console.WriteLine("Animal is eating.");
}
}
class Dog : Animal {
public void Bark() {
Console.WriteLine("Dog is barking.");
}
}
class Cat : Animal {
public void Meow() {
Console.WriteLine("Cat is meowing.");
}
}
.NET Core does not support multiple inheritance with classes directly. However, it can be achieved through interfaces. A class can implement multiple interfaces, thus inheriting the behavior defined in those interfaces.
interface IAnimal {
void Eat();
}
interface IPet {
void Play();
}
class Dog : IAnimal, IPet {
public void Eat() {
Console.WriteLine("Dog is eating.");
}
public void Play() {
Console.WriteLine("Dog is playing.");
}
}
Hybrid inheritance is a combination of two or more types of inheritance. Since C# does not support multiple inheritance with classes, hybrid inheritance is typically achieved using interfaces.
i...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào