Apologies if my terminology is incorrect, I have only started Java (and OO programming in general) 6 weeks ago.
A homework assignment has given me an interface class:
public interface Example {
void Function();
//etc
}
And then I have a couple of classes that “implement” that interface class, eg:
public class myExample1 implements Example {
void Function(){ stuff;}
public void myExclusiveFunction() { stuff;}
...
}
Inside the myExample1 class, I define the functions inside Example, but also add some specific functions to the myExample1 class.
In my main program, I have created a LinkedList<Example> eList = new LinkedList<Example>. Inside that Linked List, I am storing multiple types of Examples (myExample1, myExample2, etc). I want to do something like:
eList.get(i).myExclusiveFunction();
However this will not work. The compiler tells me:
The method myExclusiveFunction() is undefined for the type Example.
How can I use this function? I really want to have the LinkedList be able to hold objects of any Example subclass, and I am under an assignment restriction to NOT edit the Example interface.
Well you have 2 options:
1 – Change your LinkedList to store
myExample1instead ofExample.2 – Use
instanceofand cast the class to the typemyExample1(messy).