A simple request to create an object

Hi StackOverflowers

This is almost certainly a very simple question about creating an object, but in the following code example:

List myList = new LinkedList(); 

Is this a form of inheritance? In other words, would it read that LinkedList is a "list" and therefore inherits methods defined in the List class? If so, if the user created two classes of his own and used the same syntax as above, will the answer be the same?

Thanks to everyone.

Caitlin

+4
source share
3 answers

Is this a form of inheritance?

Not.

will it read that LinkedList is a "list

Yes.

and therefore inherits the methods defined in the List class?

Not. List is an interface and therefore cannot be extended / inherited (only implemented). But LinkedList still runs as IS-A because it implements all the methods required by the List interface.

If the user created two classes of his own, and one of them is the base class and the other derived , then yes, this will be inheritance. But the following

 BaseType base = new SubType(); 

definitely does not demonstrate inheritance, but polymorphism makes inheritance possible, i.e. since the base type of the auxiliary type IS-A can also be bound to the base type.

+5
source

Not really, because List is an interface that implements LinkedList , not a superclass from LinkedList . You should familiarize yourself with the interfaces. There is no inheritance of List methods; instead, there is simply a requirement that LinkedList have the methods listed in the List interface.

+4
source

There is a principle that states: "Always program the interface, not the implementation." LinkedList is an implementation of the List interface. That is, List simply indicates what List can do, but does not say how it does it.

The LinkedList class “obeys” the specification of the list, and as such, when we write programs, we can depend on the LinkedList, which behaves exactly as specified in the List. This makes programs more reliable, because if you decide to use a different List type, say ArrayList, then your program code will not change, because you are not dependent on the details of the List implementation.

When you declare a variable as in

  List myList; 

The list type is called the "visible" type. That is, the compiler will treat myList as a list in the rest of your code. You cannot refer to any function myList, which is not included in the List specification (without casting and violation of the principle).

When you instantiate an object, as in

  = new LinkedList(); 

The LinkedList type is known as the "actual type". The compiler does not care about this so much. This only matters at runtime.

+1
source

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


All Articles