英文:
Why can't we define (assign a value) a variable (field) after it is declared in a class?
问题
在一个普通的类中,
public class MyClass {
int a = 12;
}
是可以正常工作的。
但是,
public class MyClass {
int a = 12;
int b;
b = 13;
}
会产生编译错误。
我知道我在不使用该类的对象的情况下尝试访问一个字段,所以我甚至尝试了这个->
public class MyClass {
int a = 12;
int b;
MyClass m = new MyClass();
m.b = 13;
}
但是即使这样似乎也不起作用。
我可以接受这就是事实,然后继续。但是有人知道背后的逻辑吗?
提前谢谢。
英文:
In a normal class,
public class MyClass {
int a =12;
}
works fine.
But,
public class MyClass {
int a =12;
int b;
b=13;
}
this gives a compilation error.
I know I am trying to access a field without using an object of that class, so I even tried this->
public class MyClass {
int a =12;
int b;
MyClass m= new MyClass();
m.b=13;
}
but even this doesn't seem to work.
I can accept the fact that this is how things work and move on. But does anyone know the logic behind this?
Thank you in advance.
答案1
得分: 1
int a = 12;
这是一个带有初始化的变量声明。
b = 13;
这是一个赋值语句;一个语句;它不能是声明的一部分。它必须是构造函数或方法的一部分。
这是Java对象定义的工作方式。
- 变量/字段声明
- 构造函数
- 方法(静态或非静态)
英文:
int a = 12;
This is a variable declaration with initialisation.
b=13;
This is an assignment; a statement; it cannot be part of the declaration. It has to be part of the constructor or method.
It is how Java object definition works.
- variable/field declarations
- constructors
- methods (static or non-static)
答案2
得分: 0
你可以通过以下两种方式之一完成:
-
使用初始化块,如下所示:
int b;
{
b = 13;
} -
在构造函数中执行以下操作:
b = 13;
请访问 https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html 了解更多信息。
英文:
You can do it in one of the following two ways:
-
Use the initialization block as follows:
int b; { b = 13; }
-
Do the following in the constructor:
b = 13;
Check https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html to learn more about it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论