开发者

Using object variables inside other classes

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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜