Using objects/inherited classes in Linked Lists
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 thi开发者_开发百科s 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 myExample1
instead of Example
.
LinkedList<myExample1> eList
2 - Use instanceof
and cast the class to the type myExample1
(messy).
Example exObj = eList.get(i);
if (exObj instance of myExample1) {
((myExample1)exObj).myExclusiveFunction();
}
You need to learn about casting in Java. Yours doesn't work because myExclusiveFunction() only exists in Example and not in myExample1 (you might want to follow the right Java Naming convention here)
When you get the item from the list eList.get(i), you will get Example as a return type and not myExample1. In order to use myExclusiveFunction(), you need to first convert the type from Example to myExample1. Search for "type casting in Java" or "casting operator" in Google
put the myExclusiveFunction logic inside Function().
you can only call functions that are in the interface like Function
精彩评论