The syntax using only this would also make sense. Anyway it's the idea that matters. Using type parameters wouldn't work. The main issue is that you need to somehow tell the compiler that the type returned is the type of the called object. This is not possible using generics, as there is no way to specify that a type variable must equal the class. E.g. it is not possible in java to write something like the following:
public abstract class Base implements Comparable<this> { }
public class Child extends Base { private int foo; public int compareTo(Child object) { return foo - object.foo; } }
While Child would not be a proper sublcass of Base, it would be restricted further by Base. Note that such a language feature would mean that extending classes must always override the affected methods, and that they would not be proper subclases of Base.
> Yes there will be an unchecked warning that you would > supress. It is a pity that the type checking in Java > can't do the example without a cast.
It can't do this because it cannot be guaranteed that this is an instance of T. The compiler's warning is correct.
publicclass Test
{
publicstaticvoid main(String[] args)
{
A a = new B().f();
//B b = new B().f(); does not compile
}
}
abstractclass HasF< T extends HasF< T > > {
@SuppressWarnings( "unchecked" )
T f() {
System.out.println( "HasF.f()" );
return (T)this;
}
}
class A extends HasF<A>
{
}
class B extends HasF<A>
{
}
> The compiler is perfectly reasonable here. > > A class is not required to have return types covariant. > So, imagine a class that did not made the return type > convariant. > > <code> > class Foo extends HasF{ > public HasF f() { .... } > } > </code> > > Now, it's clear that manipulate() is bogus! > Imagine Manipulator4<Foo> > The manipulate() method thinks its return type is Foo but > the call to obj.f() returns HasF.
Exactly. The 'puzzle' assumes (or implies) a falacious argument: That because the A subclass of F can narrow the return type of f() that it will narrow it to the sublcasses type.
The above is a clear counter-example.
Flat View: This topic has 17 replies
on 2 pages
[
«
|
12
]