C # Basic Getting started seven interfaces
- Because the C # language does not support multiple inheritance, you can use interfaces to emulate the inheritance of structs, and define an interface by using the interface keyword.
interface USB{ void Read(string[] datas);}
- An interface is very similar to an abstract class, it defines some properties and methods that are not implemented, and all inherited classes inherit these members, and in this perspective, interfaces can be understood as a template for a class, and the ultimate purpose of the interface is to play a unifying role.
- Any class or struct that implements an interface must implement the methods of all its members;
- Interfaces cannot be instantiated directly, but can be instantiated indirectly by pointing to subclasses;
- An interface can contain declarations of methods and properties, but cannot contain fields;
- All methods and properties in the interface are public by default and cannot be added later;
- A class or struct can implement multiple interfaces, and a class can inherit a base class and implement one or more interfaces.
- Abstract classes can have non-abstract members in addition to abstract members, whereas all members of an interface are abstract
- Abstract members can be private, while interface members are public by default
- The interface cannot contain constructors, destructors, static members, and constants
- C # only supports single inheritance, where subclasses can inherit only one parent class, while a subclass can accept implementing multiple interfaces.
Practice
- Calculate the surface area and volume of the ball
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace ballcalculation{interface Iarea {void area ();//method of calculating sphere size} interface Ivolume {VO ID Volume (); } public class Ballcalculation:iarea, ivolume {public void area () {Console.WriteLine ("please Enter the radius of the ball "); int r = convert.toint16 (Console.ReadLine ()); Double AR = 4 * Math.PI * R * r; Console.WriteLine ("Spherical surface area is {0}", AR); } public void Volume () {Console.WriteLine ("Enter the radius of the sphere"); int r = convert.toint16 (Console.ReadLine ()); Double Vol = Math.PI * R * R * r * 4/3; Console.WriteLine ("Ball volume is {0}", vol); }} class Program {static void Main (string[] args) {ballcalculation ballcal = new ball Calculation (); Iarea IAR = (iarea) ballcal; Ivolume Ivol = (IVoLume) ballcal; Iar. Area (); Ivol. Volume (); } }}
- The effect is as follows: (Fig. 13)
C # Basics Get started Seven