Sorry for the title, couldn't come up with anything clearer.
I have the following structure:
public interface Vehicle {...}
public class Car implements Vehicle {...}
then:
public abstract class Fixer {
...
abstract void fix(Vehicle vehicle);
...
}
and would like to have:
public class CarFixer extends Fixer {
void fix(Car car) {...}
}
but this doesn't work. Eclipse says: The type CarFixer must implement the inherited abstract method Fixer.fix(Vehicle). Any idea how can I solve this?
You can use Generics to solve this:
public abstract class Fixer<T extends Vehicle> {
abstract void fix(T vehicle);
}
public class CarFixer extends Fixer<Car> {
void fix(Car car) {...}
}
The problem with your original version is that the fix method allows any type of vehicle, but your implementing class allows only cars. Consider this code:
Fixer fixer = new CarFixer();
fixer.fix(new Bike()); // <-- boom, `ClassCastException`, Bike is a vehicle but not a car
You've met the humble home of generics.
Generics provide kind of 'wildcard' type where a class or method can specify that 'we don't really care what type it is, we just need -a- type'.
Generics allow a super class to enforce a specific type in a child class instead of allowing any class that extends a certain class.
This means that you're ultimately enforcing a new highest allowed super-class as the parameter (i.e. Vehicle is no longer the most basic allowable type you can pass to fix(); it's now whatever the subclass says it is, so long as that arbitrary type extends Vehicle).
Common places for generics are container classes (i.e. List, Map, and Set) where the container doesn't really care about what type it tracks, but rather focuses on actually tracking and managing those instances.
Generics consist of one or more type placeholders (in Java, E and T are commonly used but the name doesn't really matter; they usually follow the normal type naming conventions) that are used in place of a specific class or super class.
In your code, you want subclasses to implement methods given their exact relevant types (i.e. a CarFixer would take Cars, a JetpackFixer would take Jetpacks) but you want to enforce that these types extend Vehicle.
In order to enforce this, you have to tell the Fixer class exactly what your subclass wants.
public abstract class Fixer <E extends Vehicle>
{
abstract void fix(E vehicle);
}
Your subclass then extends Fixer, filling in E with the type it wants.
public class CarFixer extends Fixer<Car>
{
#Override
void fix(Car vehicle)
{
// ...
}
}
Related
Consider the following situation:
public abstract class AnimalFeed{
}
public class FishFeed extends AnimalFeed{
}
public class BirdFeed extends AnimalFeed{
}
public abstract class Animal{
public void eat(AnimalFeed somethingToEat)
}
Now I would like to define a class "Bird" extending "Animal" being sure that when the bird eats, it eats only BirdFeed.
One solution would be to specify a sort of contract, in which the caller of "eat" must pass an instance of the appropriate feed
public class Bird extends Animal{
#Override
public void eat(AnimalFeed somethingToEat){
BirdFeed somethingGoodForABird
if(somethingToEat.instanceOf(BirdFeed)){
somethingGoodForABird = (BirdFeed) somethingGoodForABird
}else{
//throws error, complaining the caller didn't feed the bird properly
}
}
}
Is it acceptable to delegate the responsibility of the parameter to the caller? How to force the caller to pass a specialization of the parameter? Are there alternative design solutions?
You'd need to add a type variable to the class:
public abstract class Animal<F extends AnimalFeed> {
public abstract void eat(F somethingToEat);
}
Then you can declare your subclasses as wanting a particular type of AnimalFeed:
public class Bird extends Animal<BirdFeed> {
public void eat(BirdFeed somethingToEat) {}
}
public class Fish extends Animal<FishFeed> {
public void eat(FishFeed somethingToEat) {}
}
What you are asking for doesn't make sense from an theoretical point of view.
Restricting a method parameter violates the Liskov Substitution Principle.
The idea there: any occurance (usage) of some base class object must be able to deal with some sub class object, too.
A more simple example: when your base interface goes:
void foo(Number n)
then you must not do
#Override
void foo(Integer i)
in a subclass. Because all of a sudden, a caller
someObject.foo(someNumber)
would run into ugly ugly problems when someObject is of that derived class; which only accepts Integers, but not Numbers.
In other words: good OO design is much more than just writting down A extends B. You have to follow such rules; or you end up with systems are already broken on a conceptual point!
And for the record: it is theoretically valid to widen method parameters (in general, but in Java); and it is also ok to restrict the return types of methods (because these changes can not break client code; and that even works in Java).
Long story short: the answer here is too change your design; for example by using Generics and dependent interfaces to somehow create a relationship between the Animal and the Feed class hierarchy.
I know that I can't do this:
public abstract class DTODomainTransformer<T, S> {
public abstract S transform(T);
public abstract T transform(S);
}
Because I get the compiler complaint:
Method transform(T) has the same erasure transform(Object) as another method in type Transformer<T,S>
I understand that is because both T and S could be extending same class. So doing this way i can tell him "No, they are not the same, so take it easy"
public interface Transformer<T extends AbstractDTO , S extends AbstractDomain> {
public abstract S transform(T object);
public abstract T transform(S object);
}
Then, my question is, is there any way to tell the compiler that T and S extend from different classes without telling which ones in concrete? I mean, in this last case, I've specified which classes had to be T and S (extending respectively). But what if I want it more generic and not specify them? I'd like to tell the compiler, "Hey, compiler, T and S are not the same! They are different classes. I don't know exactly which classes they are, but I'm sure that they are different".
There's not an obvious way. (Although you can build one, as I show below.)
This overload rule is due to a limitation of how the supertype (in this case, interface) that declares the overloads gets translated (by erasure) to bytecode.
If there's a generic parameter declared T, a method that uses T in its signature will have bytecode generated as the upper bound of T, for example
class Generic<T> {
void work(T t) {}
}
will get erased to
class Generic {
void work(Object t) {}
}
and
class Generic<T extends Number> {
void work(T t) {}
}
will get erased to
class Generic {
void work(Number t) {}
}
This is how the bounded example works, because the overloads erase differently.
public interface Transformer {
public abstract AbstractDomain transform(AbstractDTO object);
public abstract AbstractDTO transform(AbstractDomain object);
}
But without specific bounds, what erased bytecode should be generated for the overloaded methods?
So your T and S being different on the subtype is not what's important. What is important is the known declared bounds which get translated to erased bytecode for the supertype class.
A possible solution could use marker interfaces.
interface TransformT {}
interface TransformS {}
interface Transformable extends TransformT, TransformS {}
interface Transformer<T extends TransformT, S extends TransformS>
T transform(S s);
S transform(T t);
}
abstract class AbstractDTO implements Transformable {}
abstract class AbstractDomain implements Transformable {}
new SomeTransformerImpl<AbstractDTO, AbstractDomain>()
But I don't necessarily recommend doing this. It seems elaborate to me, although interesting. It depends on how complicated the actual class hierarchy is.
What Louis suggested in the comments is much simpler: give the methods different names.
Lets say I have an abstract class:
public abstract class Trainer<T extends Animal>{
...
}
I'd like all child classes to have a common method that checks the training status of a trainer on a given animal. So I have in my Trainer definition:
public abstract class Trainer<T extends Animal>{
public double getStatus(Animal a){
...
}
}
so that anyone can query a trainer regardless of it's specific type. However, to make the individual trainers responsible for reporting their own status, I requiring a that the individual trainers implement an internalGetStatus method which I'd then like my getStatus method to call. So what I'm currently doing is:
public abstract class Trainer<T extends Animal>{
protected abstract internalGetStatus(T theAnimal);
public double getStatus(Animal a){
return internalGetStatus((T) a);
}
}
The problem is, of course, return internalGetStatus((T) a); involves an unchecked type cast which throws up a warning I'd like to avoid.
Is there a way to do that?
Because of some design limitations beyond my control, when the status is being queried for a particular animal, it is provided as an object of the parent class Animal and not the specific animal type that the trainer is created for.
It depends on how the classes are used. However, you didn't say much about that. Let's start with the following code:
abstract class Animal { }
final class Lion extends Animal { }
abstract class Trainer<T extends Animal> {
public abstract double getStatus(T animal);
}
final class LionTrainer extends Trainer<Lion> {
public double getStatus(Lion lion) {
return 4.2;
}
}
You mentioned that the call-side of the getStatus method doesn't know the animal type. That means he isn't using Trainer<Lion>, but either the raw type, Trainer<Animal> or a wildcard type. Let's go through these three cases.
Raw Type: The type parameter doesn't matter for raw types. You can invoke the method getStatus with Animal. This works as long as the sub-types of Trainer and Animal match. Otherwise, you will see a ClassCastException at runtime.
void raw(Trainer trainer, Animal animal) {
trainer.getStatus(animal);
}
Trainer<Animal>: Obviously, you can invoke the method getStatus of an Trainer<Animal> with an Animal. It similar to the above case. The static type system doesn't ware, and at runtime you will see an exception, if the types don't match.
void base(Trainer<Animal> trainer, Animal animal) {
trainer.getStatus(animal);
}
Note that you can pass a LionTrainer to this method (with cast), because at runtime there is no difference between Trainer<Animal> and Trainer<Lion>.
Wildcard Type: Well, that does not work on the caller-side - without casting the Trainer<?> to something else. The ? stands for an unknown sub-type of Animal (including the base class itself).
void wildcard(Trainer<?> trainer, Animal animal) {
trainer.getStatus(animal); // ERROR
}
The result is, if the framework uses either the raw type or the base type, then there shouldn't be a problem. Otherwise it's simpler to add the cast to your code, suppress the warning with an annotation, and document why you have decided to go that way.
Suppose I have the following situation:
public abstract class Vehicle {
public void turnOn() { ... }
}
public interface Flier {
public void fly();
}
Is there a way that I can guarantee that any class that implements Flier must also extend Vehicle? I don't want to make Flier an abstract class because I want to be able to mix a few other interfaces in a similar manner.
For instance:
// I also want to guarantee any class that implements Car must also implement Vehicle
public interface Car {
public void honk();
}
// I want the compiler to either give me an error saying
// MySpecialMachine must extend Vehicle, or implicitly make
// it a subclass of Vehicle. Either way, I want it to be
// impossible to implement Car or Flier without also being
// a subclass of Vehicle.
public class MySpecialMachine implements Car, Flier {
public void honk() { ... }
public void fly() { ... }
}
Java interfaces cannot extend classes, which makes sense since classes contain implementation details that cannot be specified within an interface..
The proper way to deal with this problem is to separate interface from implementation completely by turning Vehicle into an interface as well. The Car e.t.c. can extend the Vehicle interface to force the programmer to implement the corresponding methods. If you want to share code among all Vehicle instances, then you can use a (possibly abstract) class as a parent for any classes that need to implement that interface.
You could rearrange your classes and interfaces like this:
public interface IVehicle {
public void turnOn();
}
public abstract class Vehicle implements IVehicle {
public void turnOn() { ... }
}
public interface Flier extends IVehicle {
public void fly();
}
This way all implementations of Flier are guaranteed to implement the protocol of a vehicle, namely IVehicle.
If you have control on the Vehicle classes just extract Vehicle as an interface and then provide a base implementation.
If you have no control over Vehicle class, for example because it is part of a framework you are using or a third party library, it's not possible to do in Java.
The closest thing you can do is using Generics multiple wildcards notation.
<T extends Vehicle & Car>
But you can't really apply it directly to Car unless you do something like this:
public interface Car<T extends Vehicle & Car>() {
T self();
}
Which is bot weird and do not enforce the self method to actually return self, it's just a strong hint/suggestion.
You would implement a Car like this:
public class CitroenC3 extends Vehicle implements Car<CitroenC3> {
#Override
public CitroenC3 self() {
return this;
}
}
one can use a Car<?> like this:
Car<?> car = obtainCarInSomeWay();
Vehicle v = car.self();
Car c = car.self();
they should be both valid syntax.
What the compiler enforce here is that what you specify in Car<WHICH> as WHICH must both extend Vehicle and implement Car. And by adding self() you are saying to the programmer that the T object is supposed to be the object itself, thus forcing the wildcard instance to match the class if he want to be compliant with the specification.
in Java 8 you can even define a default implementation for the self method.
I also wish there was a better way to handle something like this.
It's a strange requirement, but you can accomplish something of the sort with Generics:
<T extends MyInterface & MyAbstractClass>
This question shows that you haven't grasped the essence of interface and class. Forgetting the concrete Java syntax right now, all you need to understand first is that: interface is a set of protocol, which should be implementation-agnostic. It makes no sense to let an interface extend a class(which is implementation-oriented).
Back to your concrete question, if you want to guarantee that a Flier is always a kind of Vehicle, just change the latter to an interface and let former extends it(It does make sense to extend one protocol from the other protocol). After that, you may create any class(abstract or concrete) that implements Vehicle or Flier.
Define a new Package
Create a new interface (ie. HiddenOne) with scope "default" with a method "implementMe(HiddenOne)"
Move Vehicle and Flier to the new Package.
Inherit Vehicle and Flier from HiddenOne
Implement the method implementMe in Vehicle.
Now: Whenever you like to implement from "Flier" you must extends from Vehicle !
(because only Vehicle can implement implementMe).
This is tricky but works great.
I've got problem in my code in Java. I have four(important) Classes:
public class RDOutput extends OutputType
public class RDAnalysis extends AnalysisProperties
Now I'm trying to make a method in Analysis properties:
public abstract void display(ArrayList<? extends OutputType> results);
The main problem list, the objects in the ArrayList will be different subtypes of OutputType. In my class RDAnalysis I try to make specific overriding:
public void display(ArrayList<RDOutput> results) {
but eclipse says: Name clash: The method display(ArrayList) of type RDAnalysis has the same erasure as display(ArrayList? extends OutputType) of type AnalysisProperties but does not override it
I'm not familiar with Java tricks, I tried searching in documentation and I didn't find any solution to this problem.
My question is: Is that trick that I'm doing (Basic type in abstract and Extended in final function) possible in Java (if yes, how can I do that?) or do I have to make some enum to solve this?
I suggest you to introduce generic parameter to your class and use it to parametrize your method:
public abstract class A<T extends OutputType> {
public abstract void display(ArrayList<T> results);
}
public class B extends A<RDOutput> {
public void display(ArrayList<RDOutput> results) {}
}
It's because your display doesn't cover every case of the abstract method. Maybe try something like this :
public class RDOutput extends OutputType {}
public class OutputType {}
public abstract class AnalysisProperties<T extends OutputType> {
public abstract void display(ArrayList<T> results);
}
public class RDAnalysis extends AnalysisProperties<RDOutput> {
#Override
public void display(final ArrayList<RDOutput> results) {
}
}
The problem is that you try to override a method while restricting possible parameters.
=> ArrayList<? extends OutputType> accepts more possible elements than ArrayList<RDOutput> since RDOutput extends OutputType.
You break the rule that says: the concerned subclass method has to encompass at least elements of superclass one and NEVER restrict them.
So compiler avoid to valid this override.
By the way, avoid to type your reference with concrete values like ArrayList.
What about a LinkedList passed as arguments? ... prefer a more generic relevant type like List.
Problem here is that, after type erasure comes into play, the signature of the two methods are undistinguishable: they have the same return type and they can both accept a ArrayList<RDOutput> but the first one (the generic one) can also accept any ArrayList<T extends OutputType>.
This mean that, although the JVM won't be able to choose which one to call at runtime if you pass an ArrayList<RDOutput>, at the same time your display method does not override the abstract one because your method only work for lists of RDOutput, so if you pass a List<T extends OutputType> with T != RDOutput your specific implementation doesn't accept it.
You should consider using a type parameter on the whole class as suggested in other answers, or accept the fact that you won't be able to use any RDOutput specific methods in your display method without a cast.
if a method is expecting ArrayList<? extends OutputType>
ArrayList<RDOutput> cannot be passed to it, as parent type allows any child class of OutputType in arraylist.
consider a code like this
AnalysisProperties properties = new RDAnalysis();
properties.display(arraylist consisting of any child class of OutputType); //this line will cause runtime problems