I have the following interface:
interface something {
void doSomething();
}
And I have a class that implements this interface and adds another method that does not contain the interface:
public class Whatever implements something {
//Método da interface
public void doSomething() {
System.out.println("Do something !");
}
public void didSomething() {
System.out.println("Did something !");
}
}
Looking to follow the proposal of programming for an interface rather than an implementation, the code below would be correct:
public class Test {
public static void main(String[] arguments) {
Something s = new Whatever();
s.doSomething();
}
}
Now, if I want to call the specialized method of class Whatever
, from the type of variable (interface), I can not because the method is not found.
public class Test {
public static void main(String[] arguments) {
Something s = new Whatever();
s.doSomething();
//Erro, pois não acha o método
s.didSomething();
}
}
The only two ways I found were by putting the type of variable (class) or keeping the variable type (interface) but casting a method call:
public class Test {
public static void main(String[] arguments) {
//Isso...
Something s = new Whatever();
s.doSomething();
((Whatever) s).didSomething();
//Ou isso...
Whatever w = new Whatever();
w.doSomething();
w.didSomething();
}
}
1) Is there another way to access this specialized method in the concrete class that implements the interface? I thought I would use instanceof
to check if the variable is of a certain type, but it does not seem like a good choice to put tests to check if the class supports a particular method.
2) If it does not exist, what would be the advantage of using classes that have specialized methods but that implement interfaces, since the type of variable would have to be of a concrete class and not of an interface?