1
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 in 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 !");
}
}
Seeking to follow the proposal of programming for an interface and not for 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 variable type (interface), I cannot, 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 shapes I found were by putting the type of variable (class) or keeping the type of variable (interface) but casting the 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 to use a instanceof
to check if the variable is of a certain type, but it does not seem to me a good choice to keep putting tests to check if the class supports certain 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?
Actually I wasn’t thinking about specializing subclasses. I was focused on implementing an interface myself. The idea of specialization emerged as a means of trying to solve a planning problem (or lack of it) in creating the interface.
– Roberto Coelho