Introduction to C# language (Liu tiemanganese) - learning notes - interfaces and abstract classes

preface

  • Interface: a contract (or specification) that can define methods, properties, indexers and events, but cannot set specific values;
  • The interface is born for decoupling ("high cohesion, low coupling", convenient for unit testing);
  • The attributes and methods defined by the interface need to be fully implemented during inheritance.
  • Abstract class: a class whose function members are not fully implemented (instantiation is not allowed and can be derived as a base class);
  • An abstract class can contain abstract and non abstract methods. When a class inherits from an abstract class, the derived class must implement all the methods
    Abstract method of base class;
  • Abstract classes can inherit non abstract classes In addition, it is feasible to add new abstract and non abstract methods by inheriting the methods of the base class;
  • The keyword abstract and sealed cannot be used together in C# because a sealed class cannot be abstracted.

1, What is the interface?

1. Basic concepts

  • Definition: it is a specification used to declare variables, which cannot be instantiated. All declared variables need to be implemented during inheritance
  • Syntax:
    ([modifier]) interface [interface name] (: [inherited interface list])
    {
    Interface content
    }
  • realization:
// Declare interface
 interface IInformation
    {
        string Code {get;set;}	//Declare properties
        void ShowInfo();	//Declaration method
    }

// Inheritance interface
public class AInfo : IInformation
    {
        string _code;
        public string Code
        {
			get {return _code;}
			set {_code =  value;}		
		}
        public void ShowInfo()
        {
            Console.WriteLine("code:"+ Code);
        }
    }

// Implementation interface
public void main()
{
	IInformation info = new AInfo();
	info.Code = "001";
	info.ShowInfo();
}

===> Code: 001

2. Declaration and Realization

  • Explicit interface: solve the problem that two interfaces contain the same members, but two interface members implement different functions and cannot be called directly. (Syntax: interface name + period name this class member (Information.Code))
interface Information1
{
	string Code {get;set;}
	void ShowInfo();
}

interface Information2
{
	string Code {get;set;}
	void ShowInfo();
}

public class AInfo : Information1, Information2
{
	string _code;
	public string Information1.Code		//	Display interface, inheriting members of Information1
	{
		get {return _code;}
		set {_code = value;}
	}
}

matters needing attention:

  • An interface can only contain non static member functions (methods, properties, events, indexers);
  • Interfaces are only used to declare variables. These function members cannot contain any implementation code, and semicolons must be used after the body;
  • According to the management, the declaration of the interface must start with capital I;
  • An interface declaration can take any modifier. For example, public protected internal private. However, the members of the interface are all implicit public and cannot take any modifiers, including public.
  • If a class implements an interface, it must implement all the members of the interface.

2, What are abstract classes?

1. Basic concepts

  • Definition: a class whose function members are not fully implemented (instantiation is not allowed and can be derived as a base class);
  • realization:
using System;

namespace Csharp
{
    class Program
    {
        static void main(string[] args)
        {
            Vehicle v = new Car();  //Base class member subclass instantiation
            v.Run();
            v.Stop();
        }
    }

    //Abstract class. Base class members can be derived. Abstract classes are not allowed to be instantiated, but can be instantiated as base class to subclass members
    abstract class Vehicle 
    {
        public abstract void Run(); //Abstract member, do not execute

        public virtual void Stop()
        {
            Console.WriteLine("Stopped!");
        }
    }

    class Car : Vehicle
    {
        //Override the run method of the base class, override modification of the subclass, and virtual modification of the parent class
        public override void Run()
        {
            Console.WriteLine("Car is running...");
        }
    }

   
}
  • Combined with interface:
using System;

namespace Csharp
{
    class Program
    {
        static void main(string[] args)
        {
            Vehicle v = new Car();  //Base class member subclass instantiation
            v.Run();
            v.Fill();
            v.Stop();
            IVehicle info = new Truck(); //Instantiation of interface derived classes (subclasses)
            info.Fill();
            info.Run();
        }
    }

    //Interface, defining two methods: run and fill
    interface IVehicle
    {
        void Run();
        void Fill();
    }

    //Abstract class. Base class members can be derived. Abstract classes are not allowed to be instantiated, but can be instantiated as base class to subclass members
    abstract class Vehicle : IVehicle
    {
        public abstract void Run(); //Abstract member, do not execute

        public void Fill()
        {
            Console.WriteLine("Pay and fill...");
        }

        public virtual void Stop()
        {
            Console.WriteLine("Stopped!");
        }
    }

    class Car : Vehicle
    {
        //Override the run method of the base class, overrid e modification of the subclass, and virtual modification of the parent class
        public override void Run()
        {
            Console.WriteLine("Car is running...");
        }
    }

    //Truck class, inherited from interface
    class Truck : IVehicle
    {
        public void Run()
        {
            Console.WriteLine("Truck is running...");
        }
        public void Fill()
        {
            Console.WriteLine("Truck Pay and fill...");
        }
    }
}

2. Opening and closing principle

definition:

  1. Software entities shall be open to extensions and closed to modifications.
  2. When the requirements of the application change, the function of the module can be extended to meet the new requirements without modifying the source code and binary code of the software entity.
  3. Software entities include: modules, classes, interfaces and methods divided in the project.

effect:

  1. Improve code reusability;
  2. Improve software maintainability.

realization:

  1. Through "abstract constraints, encapsulate changes" Opening and closing principle (that is, define a relatively stable abstraction layer for the software through the interface or abstract class, and encapsulate the variable factors in the same specific implementation class);
  2. The abstraction has good flexibility and wide adaptability. As long as the abstraction is reasonable, it can basically maintain the stability of the software architecture. Therefore, an implementation class is often derived according to the requirements to realize the opening and closing principle.

3, Abstract classes and interfaces

1. Contact

  1. Both cannot be instantiated and can only be used to declare variables;
  2. Their derived classes can only inherit one base class (that is, they can only inherit one abstract class and can inherit any number of interfaces)

2. Differences

  1. Abstract classes are designed for reuse (that is, they are used as base classes and have decoupling functions); interfaces are designed for decoupling (that is, "high cohesion, low coupling" to facilitate unit testing)
  2. The implementation of members can be defined in abstract classes, but not interfaces;
  3. Abstract classes can contain fields, constructors, destructors, static members or constants, but interfaces cannot;
  4. Members in abstract classes can be private, internal and protected, but interface members are public by default and cannot be modified during definition;
  5. Abstract classes are not fully implemented logical classes (that is, they can have fields and non-public members, which represent specific logic); interfaces are completely unimplemented logical classes (that is, "pure virtual classes", only function members, all members are public)

3. Member derivation

Keywords: C# interface abstract class

Added by Cinquecento on Mon, 03 Jan 2022 02:58:19 +0200