Xara
Xara

Reputation: 9098

SubClass variables do not get initialized again

I have my main class from which i call my sub class.

My sub class contains some public static variables like

    public class SubClass2 extends Main {


     public static  long a = 0;
     public static  long b = 0;
     public static  long c= 0;

    public void Analyze(int number)
    {
      b=2;

    //some code
     }
    }

Where as in main i call the object of the SubClass2.I want everytime when i make the new object of the subclass2 in main then it initializes all the variables =0 but when i take the print statement of the variable b.It prints out like 4.It adds up the previous value with the new value.

enter image description here

Upvotes: 0

Views: 173

Answers (4)

user207421
user207421

Reputation: 310840

Your question embodies a contradiction in terms. Static variables are initialized once, when the class is loaded. If you want variables initialized per-instance, use per-instance (non-static) variables.

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200138

You are using static variables. These have no connection to any objects you create. They are just global, unique variables. You must erase static. By the way, it is redundant to initialize a field to 0. It is already initialized to zero.

Upvotes: 4

David M
David M

Reputation: 72840

Your fields should not be declared as static in that case. This is why they're not being initialised each time. A static field is initialised once only, then shared by every instance of the class, and depending on accessibility, also outside of the class.

The logic that led to the value 4 must be in the code you've replaced with //some code, but this ins't really relevant here.

If for whatever reason these really should be static fields that are initialised each time an instance is instantiated, then you would have to initialise them manually in the class's constructor. But I'd seriously question the design that leads to this situation...

Upvotes: 6

RhysW
RhysW

Reputation: 453

If you use the word static there will only ever be one instance of the variable that is shared between everything created that uses it. Remove static and there will be a new, but more importantly, individual variable for each time its initialised in a method.

Perhaps better wording is that instance methods can and will access shared/static variables!

Upvotes: 1

Related Questions