Pleeb0101
July 22nd, 2005, 09:25
Hello!
Being bored and jobless I'm trying to brush up on my java for the coming school-year, and I'm have some trouble with interfaces, at least I think I do...

here's the code:
test.java

public class test {

public testWatcher[] list;
public int top = 0;

public void test() {
list = new testWatcher[5];
}

public void setPop (testWatcher watcher) {
if(top < 10) {
System.out.println("Inside setPop " + watcher.toString());
list[top++] = (testWatcher)watcher;
}
}

public static void main (String[] args) {
testClass tester = new testClass();
testWatcher tw = (testWatcher)tester;
test testpop = new test();
tw.testPop();
testpop.setPop(tw);

int l;
for (l = 0 ; l < testpop.top; l++) {
tw = testpop.list[l];
tw.testPop();
}
}
}


testWatcher.java

public interface testWatcher {
public void testPop ();
}


testClass.java

class testClass implements testWatcher {
public void testPop (){
System.out.println("POP!");
}
}


Now, aside from the fact that this has lots of silly bits and hooorrrible code in it and is incomplete, I can't understand why I'm getting a Null Pointer Reference error when it gets to

list[top++] = (testWatcher)watcher;

I've tried with and without the casting, and if you run the code the testWatcher in the main function works, so why is it screwing up?

Any help GREATLY appreciated forever and ever!!

Ralinx
July 26th, 2005, 05:09
i think there are 2 problems with this code... you coded the constructor as a regular method, and didn't call that method. this means that your array never gets initialized (thus the Null Pointer Exception)

change:

public void test() {
list = new testWatcher[5];
}


to this:

public test() {
list = new testWatcher[5];
}


that should fix the Null Pointer Exception...

now to the second problem.

you instantiate an array of 5 elements (list = new testWatcher[5];) but you allow more than 5 assignments:


if(top < 10) {
System.out.println("Inside setPop " + watcher.toString());
list[top++] = (testWatcher)watcher;
}


if top equals 0 before this code is first run, this code can be run 5 times. on the 6th time top's value will be 5 and the list array won't have an available reference at index 5 (only at index 0 through 4). The 6th time you get to this code you will get another exception.

Pleeb0101
July 26th, 2005, 12:44
Thank you!!

That constructor issue has creeped into my programs before and wreaked havoc, it's really tricky to spot just glancing at the code!!

As for the second problem, yeah, I know, I threw the whole thing together in under 10 minutes just to test threads and then abandoned it when it didn't work. ;0)

Again, thanks a lot!