anonymous class as generic parameter - java

I want to create a class that gets an object from anonymous class definition to store. I used a generic typed class to achieve that. Then i want to define some operations using functional interfaces that gets this object as a parameter to work with.
Code says more than words. So have a look at this:
public class Test<T> {
#FunctionalInterface
public interface operation<T> {
void execute(T object);
}
private T obj;
public Test(T _obj){
obj = _obj;
}
public void runOperation(operation<T> op){
op.execute(obj);
}
public static void main(String[] args){
Test<?> t = new Test<>(new Object(){
public String text = "Something";
});
t.runOperation((o) -> {
System.out.println(o.text); // text cannot be resolved
});
}
}
My problem is that o.text in the implementation of the functional interface cannot be resolved. Is this some kind of type erasure consequence?
The interesting thing is that I can get this code working when I implement the functional interface in the constructor.
Have a look at this code:
public class Test<T> {
#FunctionalInterface
public interface operation<T> {
void execute(T object);
}
private T obj;
private operation<T> op;
public Test(T _obj, operation<T> _op){
obj = _obj;
op = _op;
}
public void runOperation(){
op.execute(obj);
}
public static void main(String[] args){
Test<?> t = new Test<>(new Object(){
public String text = "Something";
}, (o) -> {
System.out.println(o.text);
});
t.runOperation();
}
}
This works perfect and prints out "Something". But what is wrong with my first approach? I really don't get the problem here.

The problem is that your anonymous class still has to conform to (extend or implement) some type, and the type you've chosen is Object which doesn't have your text property. In order to refer to properties of some kind, you'll need an actual class or interface to work with, so the compiler can make guarantees about what properties and methods are available on the object.
This works.
public class Test<T> {
public static class Data {
public String text;
}
#FunctionalInterface
public interface Operation<K> {
void execute(K object);
}
private T obj;
private Operation<T> op;
public Test(T obj) {
this.obj = obj;
}
public void runOperation(Operation<T> op) {
op.execute(obj);
}
public static void main(String[] args) {
Test<Data> t = new Test<>(new Data() {{
this.text = "Something";
}});
t.runOperation((o) -> {
System.out.println(o.text);
});
}
}

In the second piece of code,
new Test<>(new Object(){
public String text = "Something";
}, (o) -> {
System.out.println(o.text);
});
compiles because the type argument of Test for the constructor call is inferred (since the diamond operator is used), and it is inferred to the anonymous type that the first argument evaluates to (the anonymous class type), and thus the second argument's type is operation<that anonymous class type>, which works.
In the first piece of code, the expression
t.runOperation((o) -> {
System.out.println(o.text); // text cannot be resolved
})
does not compile. Here, the type of the lambda is inferred based on the type of the variable t, which is Test<?>. Thus, the argument of runOperation must be operation<some unknown type>. The only argument to runOperation that will work here is null.

Test<?> t = new Test<>(new Object(){
public String text = "Something";
}, (o) -> {
System.out.println(o.text);
});
The compiler here is replacing T in Test with your anonymous class and since that class contains a variable text that's why the 2nd case works.

Related

How does the 'this' keyword play a role in overloading? [duplicate]

I have a collection (or list or array list) in which I want to put both String values and double values. I decided to make it a collection of objects and using overloading ond polymorphism, but I did something wrong.
I run a little test:
public class OOP {
void prova(Object o){
System.out.println("object");
}
void prova(Integer i){
System.out.println("integer");
}
void prova(String s){
System.out.println("string");
}
void test(){
Object o = new String(" ");
this.prova(o); // Prints 'object'!!! Why?!?!?
}
public static void main(String[] args) {
OOP oop = new OOP();
oop.test(); // Prints 'object'!!! Why?!?!?
}
}
In the test seems like the argument type is decided at compile time and not at runtime. Why is that?
This question is related to:
Polymorphism vs Overriding vs Overloading
Try to describe polymorphism as easy as you can
EDIT:
Ok the method to be called is decided at compile time. Is there a workaround to avoid using the instanceof operator?
This post seconds voo's answer, and gives details about/alternatives to late binding.
General JVMs only use single dispatch: the runtime type is only considered for the receiver object; for the method's parameters, the static type is considered. An efficient implementation with optimizations is quite easy using method tables (which are similar to C++'s virtual tables). You can find details e.g. in the HotSpot Wiki.
If you want multiple dispatch for your parameters, take a look at
groovy. But to my latest knowledge, that has an outdated, slow multiple dispatch implementation (see e.g. this performance comparison), e.g. without caching.
clojure, but that is quite different to Java.
MultiJava, which offers multiple dispatch for Java. Additionally, you can use
this.resend(...) instead of super(...) to invoke the most-specific overridden method of the enclosing method;
value dispatching (code example below).
If you want to stick with Java, you can
redesign your application by moving overloaded methods over a finer grained class hierarchy. An example is given in Josh Bloch's Effective Java, Item 41 (Use overloading judiciously);
use some design patterns, such as Strategy, Visitor, Observer. These can often solve the same problems as multiple dispatch (i.e. in those situations you have trivial solutions for those patterns using multiple dispatch).
Value dispatching:
class C {
static final int INITIALIZED = 0;
static final int RUNNING = 1;
static final int STOPPED = 2;
void m(int i) {
// the default method
}
void m(int##INITIALIZED i) {
// handle the case when we're in the initialized `state'
}
void m(int##RUNNING i) {
// handle the case when we're in the running `state'
}
void m(int##STOPPED i) {
// handle the case when we're in the stopped `state'
}
}
What you want is double or more general multiple dispatch, something that is actually implemented in other languages (common lisp comes to mind)
Presumably the main reason java doesn't have it, is because it comes at a performance penalty because overload resolution has to be done at runtime and not compile time. The usual way around this is the visitor pattern - pretty ugly, but that's how it is.
Old question but no answer provides a concrete solution in Java to solve the issue in a clean way.
In fact, not easy but very interesting question. Here is my contribution.
Ok the method to be called is decided at compile time. Is there a
workaround to avoid using the instanceof operator?
As said in the excellent #DaveFar answer, Java supports only the single-dispatch method.
In this dispatching mode, the compiler bounds the method to invoke as soon as the compilation by relying on the declared types of the parameters and not their runtime types.
I have a collection (or list or array list) in which I want to put
both String values and double values.
To solve the answer in a clean way and use a double dispatch, we have to bring abstraction for the manipulated data.
Why ?
Here a naive visitor approach to illustrate the issue :
public class DisplayVisitor {
void visit(Object o) {
System.out.println("object"));
}
void visit(Integer i) {
System.out.println("integer");
}
void visit(String s) {
System.out.println("string"));
}
}
Now, question : how visited classes may invoke the visit() method ?
The second dispatch of the double dispatch implementation relies on the "this" context of the class that accepts to be visited.
So we need to have a accept() method in Integer, String and Object classes to perform this second dispatch :
public void accept(DisplayVisitor visitor){
visitor.visit(this);
}
But impossible ! Visited classes are built-in classes : String, Integer, Object.
So we have no way to add this method.
And anyway, we don't want to add that.
So to implement the double dispatch, we have to be able to modify the classes that we want to pass as parameter in the second dispatch.
So instead of manipulating Object and List<Object> as declared type, we will manipulate Foo and List<Foo> where the Foo class is a wrapper holding the user value.
Here is the Foo interface :
public interface Foo {
void accept(DisplayVisitor v);
Object getValue();
}
getValue() returns the user value.
It specifies Object as return type but Java supports covariance returns (since the 1.5 version), so we could define a more specific type for each subclass to avoid downcasts.
ObjectFoo
public class ObjectFoo implements Foo {
private Object value;
public ObjectFoo(Object value) {
this.value = value;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public Object getValue() {
return value;
}
}
StringFoo
public class StringFoo implements Foo {
private String value;
public StringFoo(String string) {
this.value = string;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public String getValue() {
return value;
}
}
IntegerFoo
public class IntegerFoo implements Foo {
private Integer value;
public IntegerFoo(Integer integer) {
this.value = integer;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public Integer getValue() {
return value;
}
}
Here is the DisplayVisitor class visiting Foo subclasses :
public class DisplayVisitor {
void visit(ObjectFoo f) {
System.out.println("object=" + f.getValue());
}
void visit(IntegerFoo f) {
System.out.println("integer=" + f.getValue());
}
void visit(StringFoo f) {
System.out.println("string=" + f.getValue());
}
}
And here is a sample code to test the implementation :
public class OOP {
void test() {
List<Foo> foos = Arrays.asList(new StringFoo("a String"),
new StringFoo("another String"),
new IntegerFoo(1),
new ObjectFoo(new AtomicInteger(100)));
DisplayVisitor visitor = new DisplayVisitor();
for (Foo foo : foos) {
foo.accept(visitor);
}
}
public static void main(String[] args) {
OOP oop = new OOP();
oop.test();
}
}
Output :
string=a String
string=another String
integer=1
object=100
Improving the implementation
The actual implementation requires the introduction of a specific wrapper class for each buit-in type we want to wrap.
As discussed, we don't have the choice to operate a double dispatch.
But note that the repeated code in Foo subclasses could be avoided :
private Integer value; // or String or Object
#Override
public Object getValue() {
return value;
}
We could indeed introduce a abstract generic class that holds the user value and provides an accessor to :
public abstract class Foo<T> {
private T value;
public Foo(T value) {
this.value = value;
}
public abstract void accept(DisplayVisitor v);
public T getValue() {
return value;
}
}
Now Foo sublasses are lighter to declare :
public class IntegerFoo extends Foo<Integer> {
public IntegerFoo(Integer integer) {
super(integer);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
public class StringFoo extends Foo<String> {
public StringFoo(String string) {
super(string);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
public class ObjectFoo extends Foo<Object> {
public ObjectFoo(Object value) {
super(value);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
And the test() method should be modified to declare a wildcard type (?) for the Foo type in the List<Foo> declaration.
void test() {
List<Foo<?>> foos = Arrays.asList(new StringFoo("a String object"),
new StringFoo("anoter String object"),
new IntegerFoo(1),
new ObjectFoo(new AtomicInteger(100)));
DisplayVisitor visitor = new DisplayVisitor();
for (Foo<?> foo : foos) {
foo.accept(visitor);
}
}
In fact, if really needed, we could simplify further Foo subclasses by introducing java code generation.
Declaring this subclass :
public class StringFoo extends Foo<String> {
public StringFoo(String string) {
super(string);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
could as simple as declaring a class and adding an annotation on:
#Foo(String.class)
public class StringFoo { }
Where Foo is a custom annotation processed at compile time.
When calling a method that is overloaded, Java picks the most restrictive type based on the type of the variable passed to the function. It does not use the type of the actual instance.
this isn't polymoprhism, you've simply overloaded a method and called it with parameter of object type
Everything in Java is an Object/object (except primitive types). You store strings and integers as objects, and then as you call the prove method they are still referred to as objects. You should have a look at the instanceof keyword. Check this link
void prove(Object o){
if (o instanceof String)
System.out.println("String");
....
}

Using Generics to Construct Instances of Child Classes

While looking at some Java 8 code I saw some use of generics that I didn't quite understand, so I wrote my own code to emulate what was going on:
public class GenericsTest {
public static void main(String[] args) {
TestBuilder tb = TestBuilder.create(Test_Child::new);
Product<Test_Child> p = tb.build();
Test tc = p.Construct("Test");
}
static class TestBuilder<T extends Test> {
private final Factory<T> f;
public TestBuilder(Factory<T> f) {
this.f = f;
}
public static <T extends Test> TestBuilder<T> create(Factory<T> f){
return new TestBuilder<>(f);
}
public Product<T> build(){
return new Product<>(f);
}
}
static class Test {
public Test(){
}
}
static class Test_Child extends Test{
public Test_Child(String s){
System.out.println("Test_Child constructed with string '"+s+"'");
}
}
interface Factory<T extends Test> {
T create(String s);
}
static class Product<T extends Test>{
private Factory<T> f;
public Product(Factory<T> f) {
this.f = f;
}
public T Construct(String s){
return f.create(s);
}
}
}
Running this prints:
Test_Child constructed with string 'Test'
What I don't understand is:
Why don't you have to provide arguments to Test_Child::new
How calling
f.create() in the Product instance refers to the
constructor of the Test_Child class.
How you don't have to provide arguments to Test_Child::new
Since its a method reference for a representation of a lamda s -> new Test_Child(s) which is possible to create as the Factory interface ends up being a FunctionalInterface by its definition.
How calling f.create() in the Product instance refers to the
constructor of the Test_Child class.
Since that's the instance type passed through the TestBuilder, to Product both having an attribute Factory<Test_Child>. It would be much clear when you rewrite the assignment as
TestBuilder<Test_Child> tb = TestBuilder.create(Test_Child::new)
To explain further as comments inlined with the code
TestBuilder tb = TestBuilder.create(Test_Child::new); TestBuilder
// TestBuilder<Test_Child> is build with a Factory<Test_Child> attribute
Product<Test_Child> p = tb.build();
// We have build a Product<Test_Child> which has a Factory<Test_Child> attribute from above
Test tc = p.Construct("Test");
// invokes the 'create' method of the Factory which calls 'new Test_Child(s)' to print the output
The method awaits Factory<T> as the input parameter:
public static <T extends Test> TestBuilder<T> create(Factory<T> f)
And Factory is an interface with only one method:
interface Factory<T extends Test> {
T create(String s);
}
That makes it effectively a functional interface, that can be implemented by simply passing a lambda: Function<String, T> (a function that creates an instance of type T from String). Test_Child::new is such a lambda, because it consumes String and produces T.
As stated Factory is a function, that takes a String and creates T. By calling the method create, we're invoking the function.

Avoiding generic types of form Foo<ActualType extends Foo<ActualType>>

I frequently find myself wanting to write generic class definitions of the form
public class Foo<ActualType extends Foo<ActualType>>
For example in a setup like this:
public interface ChangeHandler<SourceType> {
public void onChange(SourceType source);
}
public class Foo<ActualType extends Foo<ActualType>> {
private final List<ChangeHandler<ActualType>> handlers = new ArrayList<>();
public void addChangeHandler(ChangeHandler<ActualType> handler) {
handlers.add(handler);
}
#SuppressWarnings("unchecked")
protected void reportChange() {
for (ChangeHandler<ActualType> handler: handlers)
handler.onChange((ActualType) this);
}
}
public class Bar extends Foo<Bar> {
// things happen in here that call super.reportChange();
}
public static void main(String[] args) throws IOException {
Bar bar = new Bar();
bar.addChangeHandler(new ChangeHandler<Bar>() {
#Override
public void onChange(Bar source) {
// Do something with the changed object
}
});
}
The change-event here is just an example. This is more of a general problem that I'm having whenever I would like to allow a super-class to provide functionality that is "individualized" to each specific sub-class (not sure how to phrase this better... in the example above the "individualization" is the fact that the ChangeHandler is called with an object of the actual sub-type (Bar) not with the type of the super-class (Foo) that is calling the handler).
Somehow this approach seems a bit messy to me. And it actually allows for potential issues since nothing prevents me from then defining:
public class Baz extends Foo<Bar> { /* ... */ }
Is there a cleaner alternative?
The holy grail would be some type parameter that is always defined to contain the current class, like a static version of this.getClass() that would allow me to write something like this instead:
public class Foo {
private final List<ChangeHandler<this.Class>> handlers = new ArrayList<>();
public void addChangeHandler(ChangeHandler<this.Class> handler) {
handlers.add(handler);
}
protected void reportChange() {
for (ChangeHandler<this.Class> handler: handlers)
handler.onChange(this);
}
}
Where this.Class would be equal to Bar for classes of type Bar.
It is a really abstract problem. In my opinion the short answer to "how to make this cleaner" is: only use generics where it is needed.
public class List<T extends List<T>>
What is this trying to express (substituted)? A list which only allows to hold (T extends) other lists which themselves hold Ts (List) which as we know from before are Lists which only allow to hold ... and so on. Kind of circular, I don't see how you would end up with something like that?
public interface ChangeHandler<SourceType> {
public void onChange(SourceType source);
}
Why do you want to use generics here? If you want to have a change handler which can handle several resource types, then you can either create a super class from which all actual sources inherit or you create an interface which is implemented by the sources. Like that you can exactly specify what is exposed by the sources. Alternatively the source can create a source object when notifying instead of passing "this" (then it is more like a message). For example:
public interface ChangeHandler {
public void onChange(Source source);
}
public abstract class Source {
private List<ChangeHandler> handlers;
protected int nr;
public Source(int nr) {
this.nr = nr;
}
public abstract Something getSomething();
public String toString() {
return "SRC" + nr;
}
...
private notify(int index) {
handlers.get(i).onChange(this);
}
}
public class Foo extends Source {
public Foo(int nr) {
super(nr);
}
public String toString() {
return super.toString() + "Foo";
}
public Something getSomething() {
return new Something();
}
}
You never need to cast... or do you? I'm not sure if I understand the problem.
I would recommend that we simply use <This> to represent the "self type". No need for bound, since it looks complicated, doesn't deliver the intention, and cannot enforce the constraint anyway.
public class Foo<This> {
private final List<ChangeHandler<This>> handlers = new ArrayList<>();
public void addChangeHandler(ChangeHandler<This> handler) {
handlers.add(handler);
}
#SuppressWarnings("unchecked")
protected void reportChange() {
for (ChangeHandler<This> handler: handlers)
handler.onChange( (This)this );
}
}
Notice the cast (This)this.
See also Java generics: Use this type as return type?
I never use type parameters to pass "ActualType" because then it is impossible to extend the object:
public class Bar extends Foo<Bar> {
// things happen in here that call super.reportChange();
}
public class Bar2 extends Bar{
// ...
}
Bar2 "ActualType" is still Bar, and there is nothing you can do: you won't be able to use ChangeHandlers for Bar2
To avoid the issue, the only possible fix I see is to delegate the cast operation to an other class (you could also use a default method in the ChangeHandler interface).
Here is a possibility:
public class Foo // no more type parameter
{
private final List<FooCaster<?>> casterHandlers = new ArrayList<>();
/**
* unsafe because you could register a ChangerHandler of any type.
* worst of all, everything is unchecked cast so the error could show up late.
*/
public <T> void addChangeHandler(ChangeHandler<T> handler) {
casterHandlers.add(new FooCaster<T>(handler));
}
protected void reportChange() {
for (FooCaster<?> caster: casterHandlers) {
caster.reportChange(this);
}
}
class FooCaster<T> {
protected ChangeHandler<T> ch;
protected FooCaster(ChangeHandler<T> ch) {
this.ch = ch;
}
#SuppressWarnings("unchecked")
public void reportChange(Foo f) {
ch.onChange((T)f);
}
}
}
Personnaly in the case of broadcasting changes to listener/changehandlers, I'm enclined to externalize the process to an other class, which makes it possible to use parameter types properly and avoid unsafe casts.If you are still willing to use reportChange() from within the foo object, here is a possible implementation (otherwise you could store a T reference in the Broadcaster).
public class Broadcaster<T extends Foo> {
protected final List<ChangeHandler<? super T>> changeHandlers;
public Broadcaster() {
this.changeHandlers = new ArrayList<>();
}
public void startListeningTo(T obj) {// only T type objects are accepted
obj.registerBroadcaster(this);
}
public void addChangeHandler(ChangeHandler<? super T> changeHandler) {
changeHandlers.add(changeHandler);
}
void reportChange(Foo obj) {
T o = (T)obj;
for(ChangeHandler<? super T> c : changeHandlers) {
c.onChange(o);
}
}
}
public class Foo {
private final List<Broadcaster<?>> broadcasters = new ArrayList<>();
// cannot be accessed from outside of the package, only Broadcaster.startListeningTo(T o) can be used
final void registerBroadcaster(Broadcaster<?> b) {
broadcasters.add(b);
}
public final void reportChange() {
for (Broadcaster<?> b: broadcasters) {
b.reportChange(this);
}
}
}
public class Bar extends Foo {
// things happen in here that call super.reportChange();
}
public static void test() {
Broadcaster<Bar> broadcaster = new Broadcaster<>();
broadcaster.addChangeHandler(new ChangeHandler<Bar>() {
#Override
public void onChange(Bar obj) {
// do something
}
});
//note that you can use the same broadcaster for multiple objects.
Bar b = new Bar();
broadcaster.startListeningTo(b);
b.reportChange();
}
Note that you will not be able to add changeHandlers from within Bar (but is it really the object's job to register changeHandlers for itself?).

Confusion with generics, java

I have generic class :
public class Test<T> {
private Test<? extends T> myInstance;
public Test<? extends T> getInstance () {
return myInstance;
}
public void setInstance (Test<? extends T> argType) {
this.myInstance = argType;
}
}
And I have two classes in my class hierarchy relations:
public abstract class Alphabet {
//code here
}
and
public class A extends Alphabet{
public A() {
super();
System.out.print("This is A call");
}
}
Finally I have a class where I want to store make generic class Test with particular type and set new Instance of Object -> A through setInstance() method:
public static void main(String[] args) {
List<Alphabet> list = new ArrayList<Alphabet>();
Test<Alphabet> tAlphabet = new Test<Alphabet>();
tAlphabet.setInstance(new A()); //Here is compilation ERROR
}
But I have got the compilation error in line tAlphabet.setInstance(new A());
What is the issue with my generic class?
Your instance is a Test object as it's currently written, and you are supplying it with an Alphabet object instead. You probably want your instance to be of type Alphabet:
public class Test<T> {
private T myInstance;
public T getInstance() {
return myInstance;
}
public void setInstance(T argType) {
myInstance = argType;
}
}
This way, your Test stores an Alphabet instead of another Test.
It seems you have made things more complicated than needed. You probably want this in your Test class instead of what you actually have:
private T myInstance;
public T getInstance () {
return myInstance;
}
public void setInstance (T argType) {
this.myInstance = argType;
}
With this arrangement you would be free to setInstance(new A()) on a Test<Alphabet> instance.

Generics and casting to the right type

My problem can be summed-up by this snippet:
public interface TheClass<T> {
public void theMethod(T obj);
}
public class A {
private TheClass<?> instance;
public A(TheClass<?> instance) {
this.instance = instance;
}
public void doWork(Object target) {
instance.theMethod(target); // Won't compile!
// However, I know that the target can be passed to the
// method safely because its type matches.
}
}
My class A uses an instance of TheClass with its generics type unknown. It features a method with a target passed as Object since the TheClass instance can be parameterized with any class. However, the compiler won't allow me to pass the target like this, which is normal.
What should I do to circumvent this issue?
A dirty solution is to declare the instance as TheClass<? super Object>, which works fine but is semantically wrong...
Another solution I used before was to declare the instance as raw type, just TheClass, but it's bad practice, so I want to correct my mistake.
Solution
public class A {
private TheClass<Object> instance; // type enforced here
public A(TheClass<?> instance) {
this.instance = (TheClass<Object>) instance; // cast works fine
}
public void doWork(Object target) {
instance.theMethod(target);
}
}
public class A {
private TheClass<Object> instance;
public A(TheClass<Object> instance) {
this.instance = instance;
}
public void do(Object target) {
instance.theMethod(target);
}
}
or
public class A<T> {
private TheClass<T> instance;
public A(TheClass<T> instance) {
this.instance = instance;
}
public void do(T target) {
instance.theMethod(target);
}
}
The solution is to also type A. Using a wildcard ? makes you loose the type information of TheClass and there is no way to recover it later. There are some ugly hacks you could do but your best shot is to also type A:
public interface TheClass<T> {
public void theMethod(T obj);
}
public class A<T> {
private TheClass<T> instance;
public A(TheClass<T> instance) {
this.instance = instance;
}
public void doIt(T target) {
instance.theMethod(target);
}
}
It won't break any API either.
The reason for the compile error is that the ? wildcard indicates the unknown type in Java. You may declare a variable with an unknown generic parameter, but you cannot instantiate one with it. Which means that the in your constructor the passed in generic class could have been created to hold types that are incompatible with what you are trying to later on use. Case in point:
public class A {
public static void main(String[] args) {
TheClass<String> stringHolder = null; // should constrain parameters to strings
A a = new A(stringHolder);
a.donot(Float.valueOf(13)) ; // this is an example of what could happen
}
private TheClass<?> instance;
public A(TheClass<?> instance) {
this.instance = instance;
}
public void do(Object target) {
instance.theMethod(target);
}
}
In this case the compiler is preventing you from writing code that would have been prone to bugs. As others have pointed out, you should add a generic parameter type to your A class, in order to constrain the allowed types - that will remove the compile time error.
Some suggested reading: Oracle Generics Trail

Categories