In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface. An interface reference variable only knows that methods which are declared by its interface declaration. It does not allow accessing any other variables or methods that might be supported by the objects. This concept is similar when you use a parent class reference to access a child class object.
Below are the examples to illustrate the concept of Interface References:
Speed Method implemented by Person1 Distance Method implemented by Person1 The Speed of 1st person is: 10 The distance covered by 1st person is: 50 Speed Method implemented by Person2 Distance Method implemented by Person2 The Speed of 2nd person is: 15 The distance covered by 2nd person is: 45
Explanation: In above example, we have an interface named Race an two classes Person1 and Person2 which are implementing the methods of the interface. The Person1 class has its own method named display1() and similar Person2 class its own method display2() which cannot be called by using interface reference. In order to call the methods using interface reference(here r is interface reference), you have to assign to class object to it. Like if you are assigning Person1’s object obj1 to r i.e. r = obj1; then you call the Speed() and Distance() methods that are implemented by the Person1 class. In order to call display1() method, you must have to use obj1. Similarly using r = obj2; we are calling methods of Person2 class.
Bicycle Present State: speed: 3 gear: 4
Explanation: In the above example, Vehicle is an interface and Bicycle class implements this interface. Here obj is declared to be a reference to Vehicle interface in the Main() method. Now this obj is used to refer the object bicycle of the Bicycle class.
- C# | Interface
- C# | Explicit Interface Implementation
- Difference between Abstract Class and Interface in C#
- How to set automatic delay for ToolTip in C#?
- How to set ToolTip to active in C#?
- How to set the title of the ToolTip in C#?
- How to make a balloon ToolTip window in C#?
- How to set AutoPopDelay of ToolTip in C#?
- How to set the initial delay of the ToolTip in C#?
- How to set icon in the ToolTip in C#?
- What is Regular Expression in C#?
- How to set the Background Color of the RichTextBox in C#?
- How to set the Height of the Elements present in the ListBox in C#?
- How to Add Text in the RichTextBox in C#?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : nidhi_biet