You are on page 1of 3

Sử dụng abstract class và abstract method để định hình lên cấu trúc của các class.

Abstract class không cho phép tạo lên đối tượng từ nó VD như: Animal animal = new Animal();
Muốn tạo đối tượng và sử dụng các method cần tạo một lớp (class) kế thừa (inherit) và định
hình lại cấu trúc method cho từng class con bằng override

// Abstract class

abstract class Animal

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep()

Console.WriteLine("Zzz");

// Derived class (inherit from Animal)

class Pig : Animal

public override void animalSound()

// The body of animalSound() is provided here

Console.WriteLine("The pig says: wee wee");

class Program
{

static void Main(string[] args)

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound(); // Call the abstract method

myPig.sleep(); // Call the regular method

interface cũng là một cách để định hình cấu trúc menthod của class, các phần tử trong class
interface mặc định là abstract và public, có thể là properties hoặc methods. Khi kế thừa 1 class
interface thì không cần override mà vẫn có thể thiết lập cho method. VD:

// Interface

interface IAnimal

void animalSound(); // interface method (does not have a body)

// Pig "implements" the IAnimal interface

class Pig : IAnimal

public void animalSound()

// The body of animalSound() is provided here

Console.WriteLine("The pig says: wee wee");

}
class Program

static void Main(string[] args)

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

You might also like