Interface Control Variables

I will go over to some of the basics of OO and try to understand why the use of interface reference variables exists.

When I create the interface:

public interface IWorker
    {
        int HoneySum { get; }

        void getHoney();
    }

and the class implements it:

public class Worker : Bee, IWorker
    {
        int honeySum = 15;

        public int HoneySum { get { return honeySum; } }

        public void getHoney()
        {
            Console.WriteLine("Worker Bee: I have this much honey: {0}", HoneySum);
        }
    }

why do people use:

IWorker worker = new Worker();
            worker.getHoney();

instead of using:

Worker worker3 = new Worker();
            worker3.getHoney();

What is the point of the interface reference variable if you can just set the class and use its methods and fields this way?

+3
source share
6 answers

, , , . . , , , Worker, , Worker. Worker.

, , . , , :

public void stopWorker(IWorker worker) {
    worker.stop(); // Assuming IWorker has a stop() method
}

. , IWorker.

, , IWorker.

. .

+5

, .

0

, . . , , , . , , .

, , .

0

. IWorker. , IWorker . , , - .

0

- . , , , , .

. , , . , , . , , , , , , .

0

Think of interfaces as protocols, not classes, i.e. Does this object implement this protocol as opposed to a protocol? For example, can my number object be serializable? Its class is a number, but it can implement an interface that usually describes how it can be serialized.

A given object class can actually implement many interfaces.

0
source

Source: https://habr.com/ru/post/1762225/


All Articles