简体   繁体   English

final 关键字是否在静态方法中存储变量?

[英]Does the final keyword store variables inside methods like static?

Newbie to Java here. Java新手在这里。 I'm in the process of porting my iPhone app to Android.我正在将我的 iPhone 应用程序移植到 Android。 From what I've read, the final keyword is pretty much equivalent to static .从我读到的内容来看, final关键字几乎等同于static But does it work the same inside a method?但是它在方法中的工作方式相同吗?

For example in Objective-C inside a method... static Class aClass = [[aClass alloc] init];例如在Objective-C里面的一个方法... 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(); Java 中的某些东西是否会在方法中类似于... 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.在这方面,Java 并不像Objective C ,而final更类似于const因为它表明引用不能被改变。 In your example, when the block ends the final variable will be eligible for garbage-collection as it is no longer reachable.在您的示例中,当块结束时, final变量将有资格进行垃圾收集,因为它不再可访问。 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...请注意,Java 类名称按照约定以大写字母开头...

static final MyClass aField = new MyClass();

You are confusing the meaning of Final and Static.您混淆了 Final 和 Static 的含义。

Final means that the value of the variable cannot be changed after its value is initially declared. final 表示该变量的值在其初始声明后不能更改。

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
 }     

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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