简体   繁体   中英

Does the final keyword store variables inside methods like static?

Newbie to Java here. I'm in the process of porting my iPhone app to Android. From what I've read, the final keyword is pretty much equivalent to static . But does it work the same inside a method?

For example in Objective-C inside a method... static Class aClass = [[aClass alloc] init]; wouldn't be reallocated again and it wouldn't be disposed at the end of the method.

Would something in Java inside a method like... final Class aClass = new aClass(); act the same?

不可以。当块退出时,块局部变量超出范围,并在堆栈上进行逻辑(通常是物理)分配。

Java isn't really like Objective C in that respect, and final is more akin to const because it indicates a reference may not be altered. In your example, when the block ends the final variable will be eligible for garbage-collection as it is no longer reachable. I think you want a field variable something like

static final aClass aField = new aClass();

Note that Java class names start with a capital letter by convention...

static final MyClass aField = new MyClass();

You are confusing the meaning of Final and Static.

Final means that the value of the variable cannot be changed after its value is initially declared.

Static means a variable can be accessed and changed without needing to instantiate a class beforehand.

Perhaps the following bit of code will make this more clear.

public class SF1 {

static int x;
final int y = 3;
static final int z = 5;

public static void main(String[] args) {
        x = 1;
        // works fine

        SF1 classInstance = new SF1();
        classInstance.y = 4;
        // will give an error: "The final field main.y cannot be assigned"

        z = 6;
        // will give an error: "The final field main.z cannot be assigned"

        reassignIntValue();
        // x now equals 25, even if called from the main method

        System.out.println(x);
    }

    public static void reassignIntValue() {
        x = 25;
    }
}

You have to declare your variable in class scope so you can able to access it outside of your method.

class ABC{

 int a;

 public void method(){
    a = 10; // initialize your variable or do any operation you want.  
 }


 public static void main(String args[]){

    ABC abc = new ABC();
    System.out.println(abc.a) // it will print a result
 }     

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM