14.1 class and interface inheritance
14.2 define an Interface
14.3 interface inheritance
Public static class Program
{
Static void Main (String [] args ){
//-------------------------
Console. WriteLine ("--- first example ---");
BaseClass B = new BaseClass ();
B. fun1 ();
B. fun2 ();
(Itest) B). fun1 ();
(Itest) B). fun2 ();
//--------------------------
Console. WriteLine ("--- second example ---");
SonOne s1 = new SonOne ();
S1.fun1 ();
S1.fun2 ();
(Itest) s1). fun1 ();
(Itest) s1). fun2 ();
//----------------------------
Console. WriteLine ("--- third example ---");
B = new SonOne ();
B. fun1 ();
B. fun2 ();
(Itest) B). fun1 ();
(Itest) B). fun2 ();
//----------------------------
Console. WriteLine ("--- fourth example ---");
SonTwo s2 = new SonTwo ();
S2.fun1 ();
S2.fun2 ();
(Itest) s2). fun1 ();
(Itest) s2). fun2 ();
//----------------------------
Console. WriteLine ("--- fifth example ---");
B = new SonTwo ();
B. fun1 ();
B. fun2 ();
(Itest) B). fun1 ();
(Itest) B). fun2 ();
//----------------------------
Console. ReadLine ();
}
}
Public interface Itest {
Void fun1 ();
Void fun2 ();
}
// 1. BaseClass must implement all the methods fun1 and fun2 in Itest
// 2. The interface method should be marked as virtual. If the mark is not displayed, the compiler will mark it as virtual and sealed. In this way, the derived class cannot override the interface method.
// The derived class can re-inherit the same interface and provide its own implementation.
Internal class BaseClass: Itest {
// Fun1 will be marked as sealed and cannot be overwritten
Public void fun1 (){
Console. WriteLine ("BaseClass. fun1 ");
}
Public virtual void fun2 ()
{
Console. WriteLine ("BaseClass. fun2 ");
}
}
Internal class SonOne: BaseClass {
// The derived class cannot override the base class method fun1
New public void fun1 (){
Console. WriteLine ("SonOne. fun1 ");
}
// The derived class can override the base class method fun2.
Public override void fun2 ()
{
Console. WriteLine ("SonOne. fun2 ");
}
}
Internal class SonTwo: BaseClass, Itest
{
// The derived class cannot override the base class method fun1. new indicates re-implementing the Itest fun1.
New public void fun1 ()
{
Console. WriteLine ("SonOne. fun1 ");
}
// The derived class can override the base class method fun2.
Public override void fun2 ()
{
Console. WriteLine ("SonOne. fun2 ");
}
}
Result: