简体   繁体   English

将值传递给java中的成员变量

[英]passing value to member variable in java

Why can we do this:为什么我们可以这样做:

class A{int a=5;}

but are not allowed to do this:但不允许这样做:

class A {
     int a;
     a=5;       
}

just put it inside a block then.然后把它放在一个块里。

class A {
     int a;
     {a=5;}       
}

An initialization block will run every time you make in instance of the class eg每次创建类的实例时都会运行一个初始化块,例如

new A();

this is of course between two other initializations related to creating a new instance.这当然是在与创建新实例相关的其他两个初始化之间。 first is the field's initializations like when you declare a field with a value.首先是字段的初始化,就像您用值声明字段时一样。

int a = 25;

then the block initialization然后块初始化

{
  a = 5;
}

then the constructor:然后是构造函数:

A() {
    a = 6;
}

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

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