Why can I assign an instance of a class to a variable whose type is the interface?

Asked

Viewed 53 times

3

Exactly what you mean when I create an object in memory, but I associate it with variable a1 interface-type (AreaCalculavel)? I’m a little confused, see below the example.

package exercicio0101;

public class Aplicacao {

    public static void main(String[] args) {

        double area;

        AreaCalculavel a1 = new Quadrado(10);
        area = a1.calculaArea();
        System.out.println("Area do Quadrado: " + area);

        AreaCalculavel a2 = new Circunferencia(5);
        area = a2.calculaArea();
        System.out.println("Area da Circunferencia: " + area);

        AreaCalculavel a3 = new Retangulo(10, 2.5);
        area = a3.calculaArea();
        System.out.println("Area do Retangulo: " + area);
    }
}

1 answer

4


Interfaces are contracts, so they only exist to control access to members of an object, they don’t determine what the object really is, just what they’re able to do (even when they have an implementation default of methods in it). Only concrete classes can create objects and they define how the object will be structured in memory. So the interface has no role in defining the layout memory, only the 3 classes used create objects.

Another important point to note is that objects that have interfaces are always by reference and so the variable will only have a pointer that indicates where the object is in fact, so the variable has a fixed size (always 4 or 8 bytes depending on the architecture that is running). It could not be different because you can only have objects of potentially different sizes through indirect, thus keeping the same size in the variable. The object itself is in another area (heap).

Even all this could be done with only one variable, or even without any, but what I mean is that the 3 variables that hold the object are compatible and as the value is not used more could reuse the variable, or have the variable.

Just note that the variable can only access what the interface leaves, even if the object has several other members available, remembering that it is a contract of what you can access, and I understand that it has the method calcularArea() and nothing else, so that’s all you can call it (you can even access other things of the object if you make a cast, but almost always that makes a cast something is wrong).

You may need to study type hierarchy to better understand these concepts. It is not simple to understand when several other foundations are missing, because for each explanation requires a knowledge. The construction of knowledge flows best when one first learns the fundamental concepts to apply them later.

To better understand about interface:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.