There are 3 method signatures in a Phone interface, all of which were implemented in the anonymous class definition for a smartphone. However, I want the anonymous class to have another method that is not present in the Phone interface.
Could someone please help me understand how I can invoke that method outside of the anonymous class definition?
If possible, could you also tell me where I can find this in the documentation?
public class App {
public static void main(String[] args) throws Exception {
Phone smartPhone = new Phone() {
@Override
public void turnOn() { System.out.println("Turning on..."); }
@Override
public void turnOff() { System.out.println("Turning off..."); }
@Override
public void makeCall() { System.out.println("Calling..."); }
public void launchCamera() { System.out.println("Launching camera..."); }
};
// smartPhone.launchCamera(); -> This does not work...
}
}
Fun fact: the var
keyword gets you there.
You see, when you do:
SomeType myVar = new SomeType() { ...
then the compiler takes the "easy" route, and only remembers: myVar
is of type SomeType
.
But when you do:
var myVar = new SomeType() { ...
then the compiler actually determines the very specific special type that is defined on the right hand side. And then any additionally defined method is in fact "visible" and you can invoke it.
See this edition of the JavaSpecialists newsletter for more details.