在类内部方法外进行加法操作

huangapple go评论69阅读模式
英文:

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);
	}

}

huangapple
  • 本文由 发表于 2020年9月8日 18:27:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63791982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定