Câu hỏi phỏng vấn .NET Core
Câu hỏi

Explain different t...

Câu trả lời

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:

1. Single 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.

csharp Copy
class Animal {
    public void Eat() {
        Console.WriteLine("Animal is eating.");
    }
}

class Dog : Animal {
    public void Bark() {
        Console.WriteLine("Dog is barking.");
    }
}

2. Multilevel Inheritance

Multilevel inheritance occurs when a class is derived from another derived class, forming a chain of inheritance.

csharp Copy
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.");
    }
}

3. Hierarchical Inheritance

Hierarchical inheritance is when multiple classes inherit from a single base class.

csharp Copy
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.");
    }
}

4. Multiple Inheritance (Through Interfaces)

.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.

csharp Copy
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.");
    }
}

5. Hybrid Inheritance (Through Interfaces)

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.

csharp Copy
i...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

What is difference between .NET Core and .NET Framework?

entry

What is the .NET Framework?

junior

What is MSIL?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào