user8646027
user8646027

Reputation:

constant variables and methods in java

If we define a variable as constant variable, when we use this variable in methods do we have to put method as static ?

static final int AGE=35;

private int daysOfLife(){
return AGE*365;
}

can we define method as like this ?

Even though it is not giving me any errors but is it a good practice to read static data from instance methods?

Upvotes: 1

Views: 315

Answers (3)

Sabir Khan
Sabir Khan

Reputation: 10142

You shouldn't be only worried about variable / method being static or non - static but about other things too.

I would categorize your actions as - READ & WRITE and here you are trying to READ a default scoped , final & static variable in an INSTANCE , private method.

Concept of statics exits to logically group variables and methods so if your method has only that line and there isn't going to be anything else in that method, I would suggest to keep that grouping consistent and make either that variable an instance variable ( which doesn't make sense if variable is constant among all objects ) and change its scope to private ( if you don't wish variable to be available in same package classes ) OR mark that method as static.

Reading a final & static variable in an instance method is perfectly OK even though writing is questionable ( though final can't be written to but in case variable is not final ) .

Making that variable an instance one is favored if that variable is not going to be accessed by class name somewhere else and then if its going to be class level constant , make it static and change method to be static ( Initializing same constant field in every object will unnecessary cost you memory ) .

Upvotes: 1

B_Ali_Code
B_Ali_Code

Reputation: 65

1) there is no need to put method as static because static means it's for class when ever class start running static will run so static block is the thing will run first and only initialize once that's why it's not showing error in compile time

2) other way around we can't put initialize or use non static variable inside static block because static block will run before instance variable so compile time will catch the error

3) Variables that are declared final and are mutable can still be change in some ways; however, the variable can never point at a different object at any time .

4) so there nothing to worry about making method static

Upvotes: 0

Zaki
Zaki

Reputation: 15

As much as i know ....

The 'static' means it is used in a class scope. Meaning it can be used in the entire program. So technically they can be stored in a non-static method, but they'll still be able to be used outside of that instance.

Upvotes: 0

Related Questions