user3288346 user3288346 - 5 months ago 20
Java Question

Overriding abstract methods when using generics

I have the following classes:

Base class

public abstract class ArrayManipulation {

public <T> T[] largestSubArray(T[] a){
(((CharacterArrayManipulation)this).compare(a[0],a[1]);
return a;
}

abstract <T> boolean compare(T a,T b);
}


Sub class

public class CharacterArrayManipulation extends ArrayManipulation<Character> {

public Character[] largestSubArray(Character[] input){

super.largestSubArray(input));
}

//This is not seen as overriding
protected boolean compare(Character a, Character b){
return a==b;
}
}


I want to override the
compare
function in the sub-class
CharacterArrayManipulation
. When I try to do that, I get
CharacterArrayManipulation must either be declared abstract or implement abstract method compare(T,T) in ArrayManipulation


EDIT



I changed it to the following after the comments, it still seems to give the same error:

Base class

public abstract class ArrayManipulation<T> {

public T[] largestSubArray(T[] a){
this.compare(a[0],a[1]);
return a;
}

abstract <T> boolean compare(T a,T b);
}


Sub class

public class CharacterArrayManipulation extends ArrayManipulation<Character> {

public Character[] largestSubArray(Character[] input){

super.largestSubArray(input));
}

//This is not seen as overriding
@Override
boolean compare(Character a, Character b){
return a==b;
}
}

Answer

First of all, your super class should not have any knowledge of its sub classes, and so the implementation of ArrayManipulation.largestSubArray() should be left empty and abstract, or non-empty with a body that does not do any casting to sub classes (the casting is unnecessary as all sub classes of ArrayManipulation will have an overridden version of compare(), not just CharacterArrayManipulation).

Your super class isn't generic, as you haven't added the T generic to the class header.

public abstract class ArrayManipulation<T> { ... }

You should then remove the generic declaration from the largestSubArray() method and the compare() method.

public T[] largestSubArray(T[] a){ ... }
boolean compare(T a, T b);

You can't use an access modifier in the overriding version that is different to the overridden version.

// Note the lack of `protected`
boolean compare(Character a, Character b){ ... }

Side-note: You should use the @Override annotation when overriding methods. It will give you more applicable error messages and explicitly says that you are attempting to override a method.

Comments