C# abstract class (abstract)

Abstract class:
a. Definition:
·A class is an abstraction with the same characteristics and behavior, while an abstract class (add abstract before class) does not point out the specific details of the behavior, and its subclasses implement the corresponding behavior.
Add an abstract keyword in front of the ordinary class to be an abstract class.
A class that contains an abstract method is called an abstract class.
b. Abstract method:
A method that is only declared but not implemented is called an abstract method, and is declared with the abstract keyword.
c. Format:
access modifier abstract method return type method name (parameter list);
for example: public abstract void Fly();
d. Features:
abstract class:
·Cannot create an instance of an abstract class.
· Abstract classes cannot be declared as sealed. (C# provides a sealed modifier, which prevents other classes from inheriting from this class.)
Abstract method:
·Abstract method has no method body
. ·Abstract method must be in abstract class
. ·Abstract method must be implemented in subclass. Unless the subclass is an abstract class
(the purpose of the abstract method is to be rewritten by the subclass)
1. Design the Bird, Person and Fish classes. The Bird class implements the FlyAble abstract class, the Person class implements the TalkAble abstract class, and the Fish class implements the SwimAble abstract class, and print information.

abstract class

//抽象方法必须要在抽象类当中
//(类中有抽象方法,那必定是抽象类)
abstract class FlyAble
{
    
    
//声明方法(抽象方法)
//抽象方法默认为虚方法,但不能出现virtual
 public abstract void Fly();       
}
abstract class TalkAble
{
    
    
 public abstract void Talk();
}
abstract class SwimAble
{
    
    
 public abstract void Swim();
}

Subclass

//父类的抽象方法,子类必须都要实现
class Bird : FlyAble
 {
    
    
  public override void Fly()
  {
    
    
   Console.WriteLine("小鸟在飞");
  }
 }
class Person : TalkAble
 {
    
    
  public override void Talk()
  {
    
    
   Console.WriteLine("人在交谈");
  }
 }
 class Fish : SwimAble
 {
    
    
  public override void Swim()
   {
    
    
    Console.WriteLine("小鱼游泳");
   }
 }

test part

static void Main(string[] args)
{
    
    
  //抽象类不能被实例化,所以向上转型
  FlyAble f = new Bird();
  f.Fly();
  TalkAble t = new Person();
  t.Talk();
  SwimAble s = new Fish();
  s.Swim();
}

Note:
private, static, and final cannot appear in abstract methods (they will prevent abstract methods from being rewritten)
final: The modified class is a eunuch class. As the name implies, there will be no subclasses.

Guess you like

Origin blog.csdn.net/weixin_44706943/article/details/126116600