Search code examples
javainheritanceinterfaceimplements

When I create an object from a class that extends a specific interface, can I use this object in the place where I use this interface?


I know that I can pass an interface as an argument. Since we cannot create an object from an interface! Can I create an object from a class that extends this interface then I use this object in the place where I use this interface as an argument?

My question, since obj is an object from Final class, can I use it as a parameter here (m1(obj))? And explain to me why, please?

package aaa;

public class AAA {
    public static void m1(One one) {
      System.out.print("AAA");
    }

    public static void main(String[] args) {
      Final obj = new Final();
      m1(obj);
    }
}

interface One {
}

class Final  implements One {
}

Solution

  • Yes, you can do that. Interfaces are a way in Java to avoid multiple inheritance, i.e. declaring a class Foo to extend a class Bar and implement an interface Bar means that we have a "is a" relationship between Foo and Bar/Baz. So, "Foo is a Bar" and "Foo is a Baz" are true or in your case Final is a One. So, if a type is a subtype (or in Java implements an interface) the subtype can be used in place of the type or the interface (see the Liskov substitution principle).

    When you declare a method m1(One one), you require the first parameter to be of type One and as Final is a One this is obviously true.

    Please note, that even though you pass in an object of type Final the method only "sees" the interface part of the object without casting it.