I am having an issue with override (something I am fairly new with), I will post my problem specifically.
I have made a class that extend ArrayList
.
I have a few questions regarding what I have to do and regarding overrides.
Firstly, if ArrayList
implements and extends all it needs to, will my new class which extends ArrayList
also "automatically" extend and implement the necessary classes and interfaces. I am tempted to assume yes because I know you can only extend one class.
My second problems is about overrides.
I have overridden the method get()
from:
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
to:
@Override
public E get(int index) {
DoSomethingWithIndex...
return elementData(index);
}
NOTE: I have included the code above get in the source. the E elementData
...
I did not overwrite this though.
My problem is that I am told that elementData
(the return of my overridden get method) cannot be found. Should I also override it? Is it not extended with ArrayList
. I do not understand why it cannot be found.
Yes. For example, the class below is perfectly valid:
No need to implement anything or mention any interfaces.
That's right.
elementData
is private and can't be accessed in subclasses. Instead, useLastly, extending ArrayList is rarely the right thing to do. You should almost always favor composition over inheritance. See for instance: