using System;namespace InterfacesExample
{// 定義接口public interface INBAPlayable{void KouLan();}public interface ISupermanable{void Fly();}// 基類public class Person{public void CHLSS(){Console.WriteLine("人類吃喝拉撒睡");}}// Student 類實現多個接口public class Student : Person, INBAPlayable, ISupermanable{public void KouLan(){Console.WriteLine("學生可以扣籃");}public void Fly(){Console.WriteLine("學生會飛");}public void Study(){// 示例方法}}// teacher 類實現多個接口public class Teacher : INBAPlayable, ISupermanable{public void Fly(){Console.WriteLine("教師會飛");}public void KouLan(){Console.WriteLine("教師會扣籃");}}class Program{static void Main(string[] args){INBAPlayable nBA = new Student();nBA.KouLan();INBAPlayable nBA1 = new Teacher();nBA1.KouLan();Person p = new Student();p.CHLSS();Console.ReadKey();}}
}
代碼分析
- 接口定義:
iNBAPlayable
?接口定義了一個方法?KouLan()
。iSupermanable
?接口定義了一個方法?Fly()
。
- 類實現:
Student
?類繼承自?Person
?類,并實現了?iNBAPlayable
?和?iSupermanable
?接口。teacher
?類實現了?iNBAPlayable
?和?iSupermanable
?接口。
- 多態性:
- 在?
Main
?方法中,iNBAPlayable
?接口類型的變量?nBA
?和?nBA1
?分別被賦值為?Student
?和?teacher
?類的實例。通過接口調用?KouLan()
?方法,展示了多態性。