I'm working with Google Web Toolkit, and I'm having problems implementing a generic interface. I'm not really familiar with generics, doing an upgrade on someone else's code here.
Here's what I want to do: I want to have an implementation of a generic callback interface that does some logging, and then subclass that implementation in order to handle specific callback scenarios.
The interface is something like this:
public interface AsyncCallback<T> {
void MethodFromAsyncCallback(T result);
}
The abstract and concrete implementations look something like this:
class CallbackBase implements AsyncCallback<Object> {
public abstract void doStuff(Object result);
public void MethodFromAsyncCallback(Object result) {
// IMPORTANT STUFF
// here are things I would like to do for all callbacks, hence the superclass.
// Then we do the subclass specific things.
doStuff(result);
}
}
class SpecificCallback extends CallbackBase
{
public void doStuff(Object result) {
Integer i = (Integer)result;
// do stuff with i
}
}
The callbacks are required to be fired from
public interface MyServiceAsync {
public void DoSomeThing(AsyncCallback<Integer>);
}
And then it all comes together in a call that looks like this:
MyServiceAsync myService = (MyServiceAsync)GWT.create(MyServiceAsync.class);
myService.DoSomeThing(new SpecificCallback());
And here's where we have a problem!
When the GWT.create() implements the interface I created, it demands that the type given to AsyncCallback is specified (matches a type elsewhere, outside the scope of this question), hence making DoSomething(AsyncCallback<Integer>) an Integer rather than an Object. This is beyond my control.
It complains that DoSomething() takes AsyncCallback<Integer>. I'm giving it something that inherits from something that is an AsyncCallback<Object>. I guess with generics, concepts of inheritance get somewhat broken?
So my question is this:
Either how can I mush this together so that DoSomething() will recognize that that SpecificCallback meets it's requirements,
or how can I structure the relationship between CallbackBase and SpecificCallback so that duplicate code is avoided, but SpecificCallback implements AsyncCallback<Integer> directly?
Thanks.
What I think you need to do is define CallbackBase like this:
abstract class CallbackBase<T> implements AsyncCallback<T> {
public abstract void doStuff(T result);
public void MethodFromAsyncCallback(T result) {
// general stuff (T is a subclass of Object)
doStuff(result);
}
}
Then you want your specific callbacks to be like this:
class SpecificCallback extends CallbackBase<Integer> {
public void doStuff(Integer result) {
// no need to cast
// do stuff with result
}
}
Then your DoSomething method, which accepts an AsyncCallback<Integer>, will accept a SpecificCallback.
(Pedantic sidenote: please start all methods with lowercase letters in Java)
Edit
For what it's worth, I'd suggest changing your design to use composition rather than inheritance. In this case, rather than using an abstract class CallbackBase and extending it, you'd use a concrete implementation of AsyncCallback<T> that might look something like this:
class GeneralCallbackWrapper<T> implements AsyncCallback<T> {
private final AsyncCallback<? super T> delegate;
public GeneralCallbackWrapper(AsyncCallback<? super T> delegate) {
this.delegate = delegate;
}
public void MethodFromAsyncCallback(T result) {
// general stuff here
delegate.MethodFromAsyncCallback(result);
}
}
Related
Is there any way in Java to enforce a subclass or interface implementation to have a constructor with a given signature?
Let's say that I´ve got either:
public interface MyInterface {
// any methods
}
or
public abstract class MyBaseClass {
// any abstract methods
}
Now, is it possible to do anything to require
public class MySubClass extends MyBaseClass {
public MySubClass(String s) { }
}
or
public class MySubClass implements MyInterface {
public MySubClass(String s) { }
}
to always have a constructor that takes a String as it´s only input parameter?
The obvious workaround is to create a factory interface with a method taking a String and inject it where required. Which is not what I would like to do.
Not really, the closest I think you can get is something like:
abstract class B {
public B(String s) {
}
}
public class A extends B {
public A(String s) {
super(s);
}
}
This forces A to implement a non default constructor which must call super(String) but can not prevent the following:
public class A extends B {
public A() {
super("");
}
}
There have been many times where I wished something like this existed, but sadly it doesn't. Even something like what David Soroko suggested wouldn't work because a subclass still wouldn't be forced to have a String constructor - it can just pass any String it likes to super. Simply put, there is no such thing within the Java syntax itself.
I suppose the closest one could get to such a capability is if someone built an annotation processor that allows you to use an annotation like #MustHaveUnaryConstructor(String.class) and then if any subclass does not have such a constructor, it causes compilation to fail and tells you which subclass broke the contract. But I haven't found such a thing and I don't know enough about annotation processing to build one myself. So TL;DR, no, you can't.
I am new to Java so i have some obvious (to some of you) questions about declaration, definition and execution of some functions.
Suppose you have declared two methods in an interface and you want to define the behavior of the first function in a (abstract?) class and the second function in another (abstract?) class.
Is there a way to define two methods in two separate classes? For example i could have a lot of methods in an interface but I want to implement just one of them because a specific object does not needs the others. How can I do that??
Java Code example :
interface DeclareFcnts {
void foo1();
void foo2();
}
abstract class Define_fcn1 implements DeclareFcnts {
public void foo1() {
// TODO Auto-generated method stub
}
}
abstract class Define_fcn2 implements DeclareFcnts {
public void foo2() {
// TODO Auto-generated method stub
}
}
class Myclass {
public static void main(String args[]) {
// How can i create an object that reference to the first function only?
}
}
If you implement an interface in a class, you must assume it will have all the interface methods declared. You must define what happens if any of these methods are invoked. Consider this:
DeclareFcnts instance = new Define_fcn1();
instance.foo2(); // what happens here?
What is your expected behavior on the second line? It could throw an exception, do nothing, (or return a value if the method wasn't void).
One option is to define the behavior in the concrete implementing class (because you cannot instantiate abstract classes), which is what you would like to avoid. Fortunatelly, in Java 8, there is another way - using default methods:
interface DeclareFcnts {
default void foo1() { /* default implementation, e.g. throw or do nothing */ }
default void foo2() { /* default implementation, e.g. throw or do nothing */ }
}
class Define_fcn1 implements DeclareFcnts {
public void foo1() { /* do something */ }
}
In this case, Define_fcn1 will inherit implementation of foo2 from DeclareFcnts much like if it inherited from a super class. You can notice that the class no longer needs to be abstract.
That said, you should try to avoid such situations. They will make unit testing, refactoring, etc., more difficult. You may possibly split your interface into multiple interfaces. If you need both methods somewhere, you can pass the interfaces separately, or, if absolutely necessary, define another interface like this:
interface Foo1Iface { void foo1(); }
interface Foo2Iface { void foo2(); }
interface BothIface extends Foo1Iface, Foo2Iface { }
I would avoid it if possible, though. You may get more suggestions if you add more details to your answer.
AFAIK it is not possible, when you are implementing an interface you are obliged to #override those methods in that interface but you can leave it as blank assuming that you would not call it. Although:
This is your Generic interface, it can be anything as long as you meet the requirements.
Credits to Pinterest.
If you are going to design a house it does not make sense to add a wheel or anything unrelated to the house. Otherwise create a separate Interface for a Car or a Bus.
An Example of Bad Design
interface GenericInterface{
public void defineDoor();
public void defineWindow();
public void defineWheel();
}
The actual implementation
class House implements GenericInterface{
#Override
public void defineDoor{
// do something
}
#Override
public void defineWindow{
// do something
}
#Override
public void defineWheel{
// does not make sense to the House.
}
}
Here is another class that implements the Generic Interface
class Car implements GenericInterface{
#Override
public void defineDoor{
// do something
}
#Override
public void defineWindow{
// do something
}
#Override
public void defineWheel{
// do something.
}
}
Though our Car fits the above Interface but since when did the House contains a wheel?. The right way to do this is to create Separate Interface for Car and House.
You can not do this!
you must declare body for your method that declared in interface and then create instance of class
or you can use java 8 default declaration for your interface methods
for example:
public interface IX
{
void sayHello();
void sayBye();
default void showInfo()
{
System.out.println("you call show Info method");
}
}
I'm trying to understand how to use generics in the form of a bounded type parameter in an interface. In this case, to avoid casting when using the bounded param in concrete implementations but I'm running into an issue. I will use the following example to illustrate my problem:
There's an interface and two concrete implementations
public abstract class Publication {
}
public class Newspaper extends Publication {
}
public class Newspaper extends Publication {
}
Then we have an interface representing a publishing house with two concrete implementations, one publishes magazine and the other newspapers
public interface Publisher {
public <T extends Publication >void publish(T publication);
}
Here are the two implementations
//DOES NOT COMPILE
public class MagazinePublisher implements Publisher{
#Override
public void publish(Magazine publication) {
//do something with the magazine, its already the type we need without casting
}
}
//COMPILES but a cast is required to get the type I want
public class NewsPaperPublisher implements Publisher{
#Override
public void publish(Publication publication) {
// Now I need to cast
Newspaper newspaper = (Newspaper)publication;
//Do some stuff here
}
}
The example maybe a bit contrived... I understand why the MagazinePublisher class doesn't compile: I'm trying to implement the method with a more specific class than defined by the contract of the publish method in the interface. So how do I user generics to avoid the cast in the NewsPaperPublisher class's publish() method?
You want to make the interface generic.
public interface Publisher <T extends Publication> {
void publish(T publication);
}
Then, instead of NewspaperPublisher and MagazinePublisher, you can just write Publisher<Newspaper> and Publisher<Magazine>.
Or if you want to provide different implementations depending on the type, you can write things like
public class NewspaperPublisher implements Publisher<Newspaper> {
#Override
public void publish(Newspaper publication) {
// do some stuff
}
}
I have a list of objects which extend from a base class. Now I want to apply a specific operation only on one instance of classes in the list.
Is the use of instanceof a good practice there? Or should I rather differ the objects by eg a custom enum?
abstract class Base;
class Foo extends Base;
class Bar extends Base;
List<Base> bases;
for (Base base : bases) {
if (base instanceof Bar.class) {
//execute my custom operation on the base object
doSomething((Bar) base);
}
}
If that approach is not that nice in general, how could I do better?
There does not really seem to be any reason to use instance of here. It might make sense to have the base class default the behavior to doing nothing and override it in extending classes when needed. This way you only override it if needed (I on.y left this as an abstract class to follow with the question its not needed for this example).
For example:
abstract class Base{
public void doSomething(){}
}
public class B0 extends Base{
#Override
public void doSomething(){//actually do something}
}
public class B1 extends Base{}
An example of using this could be something like:
public class SomeOtherClass{
public void something(List<Base> bases){
for(Base base:bases)
base.doSomething();
}
}
abstract class Base;//abstract function doSomething()
class Foo extends Base;//implements doSomething()
class Bar extends Base;//dito
List<Base> bases;
for (Base base : bases) {
base.doSomething();
}
To answer your question: it is not a good idea to use instanceof.
Instance of is not a good practice here.
Correct solution will depend on what exactly is going on inside that doSomething method.
If you do it your way then, besides other things, you violate Liskov Substitution Principle. I assume that you decided that you need these hierarchy in the first place because of something and I also assume that subtypes have some more behavior than only doSomething method. In this case, what you can do is shown below. Basically only types that should doSomething actually do it and rest of the types do something like no operation. In that way you can use these objects without needing to know what type they really are.
You should also ask yourself if you really need Base class to be abstract class. Maybe all you need is a interface. There might be better approach but basing on the information I have and what I've assumed then this seems to be alright.
public abstract class Base
{
public abstract void doSomething();
public void someOtherMethod()
{
// which does stuff
}
}
public class SubTypeWhichCanDoSomething extends Base
{
#Override
public void doSomething()
{
// actually implement method and DO something
}
}
public class DoesNothing extends Base
{
#Override
public void doSomething()
{
// does nothing
return;
}
}
// then your code looks like these
for(Base base : bases)
{
base.doSomething();
}
I wasn't sure how to properly name this question, so if its better suited to be edited, please do so. My question has to do with using generic types in an interface and then forcing the implementation into a specific type. Something like this:
public interface Test<T> {
void testMethod(Object<T> obj);
}
And then instead of allowing a generic object in an implementation of this interface, set the type somehow.
public class TestImpl implements Test<TestObject1> {
#Override
public void testMethod(TestObject1 obj) {
//Do something
}
}
public class Test2Impl implements Test<TestObject2> {
#Override
public void testMethod(TestObject2 obj) {
//Do something
}
}
Except you cannot paramaterize Object and i'm not sure how to set this sort of thing up. Is it even possible? Right now I just use generic Object, but that leaves me being forced to check the type of class being passed in for every single method and/or casting etc etc. It would be so much cleaner if I could just use generics on the interface and then specific classes on the implementation.
public interface Test<T> {
void testMethod(T obj);
}
You were close.
Then you can either write your classes the way you have them if testMethod is specific to the Class being passed in, or ...
public class TestImpl<T> implements Test<T> {
#Override
public void testMethod(T obj) {
//Do something
}
}
Now you can instantiate your class via new TestImpl<TestObject>() or new TestImpl<TestObject2>()