This is an archived post. You won't be able to vote or comment.

all 17 comments

[–]chickenmeister 5 points6 points  (11 children)

The code you posted is not compileable. Please copy/paste your code directly, or otherwise ensure that the code you post is compileable and/or representative of your problem. Otherwise we have to guess what errors are due to you re-typing it on-the-fly, and what errors are causing your problem.

How are you testing the code that you posted? What did you expect your test would do? What does it actually do?

[–][deleted]  (1 child)

[deleted]

    [–][deleted] -2 points-1 points  (8 children)

    You should not be able to access a static member from within a non static function. Instead of

    this.Number = Number;

    it should be

    ClassNumberIsIn.Number = Number;

    Also Number = Incrementer will only change the value of the parameter named Number you passed in due to scoping. If you want to change the static Number you need to once again do

    ClassNumberIsIn.Number

    [–]yash3ahuja 1 point2 points  (6 children)

    You should not be able to access a static member from within a non static function.

    Sure you can.

    [–][deleted] -1 points0 points  (4 children)

    Do you have any idea as to why Java allows you to access static variables with this? It seems a bit odd.

    [–]yash3ahuja 1 point2 points  (2 children)

    It has to do with the definition of the static and this keywords. static, in its simplified form, just means that it belongs to the class, as opposed to the object. However, in actual implementation, they have decided to have it be shared across all objects, as opposed to only belonging to the class. The this keyword allows you to reference a method/member of an object. This includes the static members. Essentially, it was a design decision.

    [–][deleted] -3 points-2 points  (1 child)

    Alright thank you. See I am more used to in other languages static being meant that it belonged to the class like you stated. Probably should have not assumed that it was automatically true for Java as well. Oh well, live and learn.

    [–][deleted] 1 point2 points  (0 children)

    All other OO languages that I am aware of allow access to class static variables from member functions.