tags:

views:

40

answers:

1

I have an object whose functions I would like to call from with in another class for example

class smo {

    int spoon = 10;

    smo() {
    }

    int get_spoon() {
        return spoon;
    }
}

class boat {

    boat() {
    }

    print_smo(Object test) {

        test.get_spoon();

    }
}

it tells me that the function get.spoon() does not exists. The error makes sense since the object hasn't been created the function can't be called, but it will exists when its run and I have passed an appropriate object of the type smo to it.

+4  A: 

Since Java has a static syntax check it needs to know the right type of your objects before running the program. And since it doesn't have any kind of type inference it's a programmer's duty to declare them in source code.

This means that to actually call the smo's method get_spoon() on a smo object you have to declare that it will be of that type and not just an Object (which is the least specific type possible in Java):

void print_smo(smo test)
{
  test.get_spoon();
}

this will work.. and will let you to call oneBoot.print_smo(new smo()).

Two side notes:

  • class names should be camelcased in this way: ClassName
  • methods and variable should be camelcased too but without first letter, eg: myLongVariable
Jack
I just found as always, immediately after asking, the answer.http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.htmlThank you though.
Doodle
@Doodle: You should accept this answer by clicking the checkmark. You should also go back to your old questions and mark the appropriate answers as accepted.
Adam Robinson
@Adam Robinson: :P theres a wait time :)
Doodle