Static and abstract (C# learning)

static

Static member : Static member variables are associated with the class and can be used as "common" variables in the class (it is a common performance). Static members do not depend on the existence of specific objects, and are operated through the class when accessing. Static members are decorated with the static keyword .
Divided into static member variables and static methods.

class Person
{
    
    
    //年龄
    public static int age;
    //设置年龄
    public static void SetAge(int age){
    
    
         Person.age = age;
    }
}

  • Static is loaded as the class is loaded, no matter how many instances of a class are created, there is only one static member.
  • Static methods can be overloaded.
  • Static members are called by the class name via dot syntax, non-static members are called by the object.
  • Static methods can only access static members, including static member variables and static methods; instance methods can access instance member variables and instance methods, as well as static members.

abstract

insert image description here

  • Abstract classes cannot be instantiated using the new keyword, because abstract classes are incomplete;
  • The abstract method must be placed in the abstract class, and the modifier abstract is added in front of the class;
  • The modifier abstract should also be added before the return value of the abstract method;
  • An abstract method has no method body, and the format is: method modifier abstract return value type method name (parameter list);
  • The abstract method must be overridden and implemented by the subclass, or make the subclass still an abstract class;
  • The access modifier of an abstract method cannot be private, otherwise it cannot be accessed by subclasses and cannot be overridden.
//抽象类 
abstract class Enemy{
    
     
     //抽象方法              
     public abstract void Attack();
}

class Dog{
    
    
     //父类中的抽象方法在子类中重写并实现
     public override void Attack(){
    
    
           Console.WriteLine("撕咬");
     }
}

Guess you like

Origin blog.csdn.net/qq_42540393/article/details/125604462