Can you create interface reference variables?

Can you create interface reference variables?

interface reference variables

It is stated in my earlier posting Can you create instance of interface? that we cannot create objects of interfaces but possible as an inner class.

Now the present question is can we create interface reference variables and if permitted what is the use of these reference variables as interface does not come with implementation. But it is fact that Java permits reference variables creation with interfaces but not objects.

I would like to say one word here – "We cannot create objects of interface but we can get".

Let us answer all these questions one-by-one and make Java a confusion-free language.

See this code.

interface reference variables

In the above simple code, Lion implements the interface Animal and by rule overrides the eat() method with some output.

Animal a1;
Lion l1 = new Lion();

a1 = l1;;

  1. a1 is interface Animal reference variable and l1 is an object of Lion.
  2. The subclass object l1 is assigned to super class reference variable a1 of Animal (where Animal is interface).
  3. When assigned, the l1 reference variable works like an object in every sense.
  4. Wha is the proof? Call eat() method with a1 as in the above code. It gets output.
  5. What a general object of a concrete class can do, the a1 can do. Try.
  6. Now you got an object of interface, but remember, you can create it like Animal a1 = new Animal().
  7. Differene is there in getting and creating, yes or not.
  8. Once assigned with subclass object, the interface variable works practically as an object.

The principle used is (we learnt in object casting), when a subclass object is assigned to a super class object (or reference variable), the super class object calls subclass overridden method.

View All for Java Conversions on 30 Topics

One thought on “Can you create interface reference variables?

  1. Datt


    in the above explanation, Can you please let me know if the reference of the interface Animal has a separate memory block allocated like an instance of Lion or its just pointing to the existing l1 object.



Leave a Reply

Your email address will not be published. Required fields are marked *