英文:
Addition outside method inside class
问题
以下操作在我在方法外部添加时出错,
下面的代码被声明为实例变量,我在类内部和方法外部执行了加法,
int a = 10;
a = a + 10;
如果我将这个操作放在方法内部,就不会有编译错误,为什么?
英文:
This below operation providing errors while i'm adding outside of the method,
the below mentioned code declared as instance variable,and i performed addition inside the class and outside the method,
int a=10;
a=a+10;
if i add this inside method then there will be no compilation errors,why??
答案1
得分: 1
在Java中,方法负责对实例变量执行操作。如果需要对实例变量进行初始化,可以使用构造函数或初始化块。
可以按以下方式操作:
int a = 0;
{
a = a + 1;
}
英文:
In Java, methods have the responsibility to perform operations on the instance variables. If an instance variable needs to be initialized, you can use constructor or initializer block.
You can do as below:
int a = 0;
{
a = a + 1;
}
答案2
得分: 0
在Java中 int a=10; a=a+10;
是不可能的。但你可以尝试这样做,可能对你有帮助。
public class AddOutsideMethod {
private static int i = 10;
private static int j = i + 10;
public static void main(String[] args) {
System.out.println(j);
}
}
英文:
In Java int a=10; a=a+10;
is not possible. but you can try this, may be helpful for you.
public class AddOutsideMethod {
private static int i = 10;
private static int j = i + 10;
public static void main(String[] args) {
System.out.println(j);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论