-
Interface
-
An interface is similar to an abstract base class, and any non-abstract class that inherits an interface must implement all members of the interface
-
Class cannot be instantiated directly
-
Interfaces can contain time, indexers, methods, and properties
-
Interface does not contain implementations of methods
-
Classes and structs can inherit from multiple interfaces
-
The interface itself can inherit from multiple interfaces
Interface modifiers: New, public, protected, internal, private, but interface members must be common
2.
Interface 1
Interface Interface1
{
int Add ();
}
Interface 2
Interface Interface2
{
int Add ();
}
Class 1
Class Class1:interface1,interface2
{
public int Add ()
// {
return 1 + 2;
// }
Display interface member implementations
int Interface1.add ()
{
return 3 + 4;
}
int Interface2.add ()
{
Return 5 + 6;
}
}
Main function
CLASS1 cl = new Class1 (); Instantiating an interface object that inherits a class
int i = CL. ADD ();
Interface1 I1 = cl; Object instantiation interface using interface inheritance class
Interface2 i2 = cl;
Console.WriteLine (CL. ADD ()); 38//If the class is an implementation method, this section will give an error
Console.WriteLine (I1. ADD ()); 7
Console.WriteLine (I2. ADD ()); 11
PS: Display interface member implementations cannot contain access modifiers, abstract, virtual, override, or static modifiers
Shows that an interface member is a member of an interface, not a member of a class, and therefore cannot be accessed directly using a class object
2. Abstract class
A. Abstract classes cannot be instantiated directly
B. Abstract classes can contain abstract members, but not in abstract classes
C. Abstract classes cannot be sealed
3. Abstract Method:
A. Abstract methods must be declared in an abstract class
B. When declaring an abstract method, you cannot use the virtual, static, private modifier
PS: Abstract method declaration introduces a new method, but does not provide the implementation of the method, because the abstract method does not provide a method implementation, so the abstract method contains only a semicolon
Abstract classes and Interfaces:
-
Derived classes can inherit only one abstract class and inherit multiple interfaces
-
The implementation of a member can be defined in an abstract class, but not in the interface
-
Abstract classes include fields, constructors, destructors, static members, or constants, which are not available in the interface.
-
Members in an abstract class can be private, protected, internal, or protected internal members, but the members of an interface must be public
Abstract classes are primarily used as base classes for object families, sharing certain key features, such as common purpose and structure
Interfaces are primarily used for classes, which differ at the base level, but can still accomplish some of the same tasks
C # interface