Let's extend the content of the preceding section to the use of interfaces. Imagine that the Child class implements a MarathonRunner interface, as follows:
interface MarathonRunner{ default void run() { System.out.println("I'm a marathon runner"); } } class Child implements MarathonRunner { void whistle() { System.out.println("Child-Whistle"); } void stand() { System.out.println("Child-stand"); } }
Let's define an obj local variable, assigning it an instance of the Child class:
class Test{ public static void main(String[] args) { var obj = new Child(); // inferred type of var obj
// is Child obj.whistle(); obj.stand(); obj.run(); } }
If the same variable is initialized using a method whose return type is MarathonRunner, its inferred type is MarathonRunner (irrespective of the type of the instance returned by it):
class Test{ public static MarathonRunner getObject() { return new Child(); } public static void main(String[] args) { var obj = getObject(); // inferred type of var obj is
// MarathonRunner obj.whistle(); obj.stand(); obj.run(); } }