Java学习1:static 和 public 不能放在方法里面
Posted yizhaoai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java学习1:static 和 public 不能放在方法里面相关的知识,希望对你有一定的参考价值。
在练习具名常量时,以fabonacci数列为例,代码和报错如下:
1 public class Fibonacci { 2 3 public static void main(String[] args) { 4 static final String Title="Fibonacci"; 5 static final int MAX=100; 6 7 System.out.println(Title); 8 int lo=1; 9 int hi=1; 10 11 System.out.println(lo); 12 while(hi<MAX) { 13 System.out.println(hi); 14 hi=lo+hi;//新的hi是原来的两个数之和 15 lo=hi-lo;//新的lo是原来的hi 16 //这里要先算hi; 17 //因为如果lo=hi; hi=lo+hi; 18 //这是错的,因为调用的lo已经变了; 19 } 20 }
第4,5行有错,报错如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: Illegal modifier for parameter Title; only final is permitted Illegal modifier for parameter MAX; only final is permitted at HelloWorld.Fibonacci.main(Fibonacci.java:4)
在https://stackoverflow.com/questions/21280038/java-error-illegal-modifier-for-parameter-only-final-permitted上找到答案:
public
and static
cannot be used inside a method definition. So this error is telling you that the only modifier allowed for a variable defined inside of a method is final
.
public
class MyClass { public String Name = "123"; }
public
says that any part of the program can read it (otherwise it could only be read by code written in the MyClass
class).
public
specifies what other code has access to it. Inside a method this doesn‘t make sense. Variables defined inside methods can only be accessed while inside that method, and once the method is complete they are thrown out. So it would be impossible for those variables to be public
.
public指类中的每一个方法可以访问它,但是在方法内部定义的变量,只要那个方法可以访问它,所以这是相矛盾的。
static
class MyClass { static String Name = "123"; }
static
says that the Name
variable is a part of the class itself, not of an instance of the class. In other words, all instances of the MyClass
class share the same Name
variable.
static
specifies how it is accessed (either on an instance of the class or through the class itself). Inside a method this doesn‘t make sense, because local variables are discarded after the method closes, so nothing else will be accessing it.
这个叫Name的变量,是MyClass这个类的一部分,而不是一个实例(instance)。所有的MyClass的instances都有Name这个部分,且值都是“123”.
final
class MyClass { final String Name = "123"; }
final
says that the value of Name
will never change once it has been assigned.
final
describes how the variable is going to be used. It makes sense within a method, because it is not about access.
finanl可以在方法内部。
修改后:
public class Fibonacci { static final String Title = "Fibonacci"; static final int MAX = 100; //移出来了 public static void main(String[] args) { System.out.println(Title); int lo = 1; int hi = 1; System.out.println(lo); while (hi < MAX) { System.out.println(hi); hi = lo + hi; lo = hi - lo; } }
以上是关于Java学习1:static 和 public 不能放在方法里面的主要内容,如果未能解决你的问题,请参考以下文章
Java,关于: public static final NumberFormat getPercentInstance()
为什么Java的main方法必须是public static void?