What does it mean to say that an interface is also a type?

I think this means that through the concept of polymorphism, a variable type can be declared as an interface type. For example: if Animal is an interface, you can specify the following:

Animal simba = new Lion(); 

Do I understand this correctly? Thanks for any help.

+4
source share
2 answers

Each object has a type (and value). * There are many types: primitive types (e.g. int ), class types (e.g. string ), enumerations, arrays (and maybe I forget about some).

The term β€œinterface” refers to a particular type of class type: it is a class that does not have member objects (safe constants) and only public methods, all of which are abstract. **

So: an interface is a special class, which, in turn, is a special type of type. Thus, interfaces are types. In your example, both Animal and Lion are types, and one of them can be converted to the other.

*) It is clear that the type says: "What is the structure of this," and the meaning says "what is the content." Type 5 is int , and its value ... well, 5.

**) This allows you to inherit from several interfaces, while in Java it is impossible to inherit from several common classes.

+1
source

An interface can act like superclass in Java, because it can take the type of its implementation.

In your example, in particular, you define Animal as the interface that implements Lion .

Because of this, you can create an Animal type Lion . The code will look like this:

 interface Animal { //do interfacing stuff } class Lion implements Animal { public Lion() { //... } //do implementing stuff } class Driver { Animal simba = new Lion(); // This works because of polymorphism. } 

You are right, however, in saying that this is an example of polymorphism .

+3
source

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


All Articles