为什么我们不能在类中声明变量(字段)后定义(赋值)它?

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

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

你可以通过以下两种方式之一完成:

  1. 使用初始化块,如下所示:

    int b;
    {
    b = 13;
    }

  2. 在构造函数中执行以下操作:

    b = 13;

请访问 https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html 了解更多信息。

英文:

You can do it in one of the following two ways:

  1. Use the initialization block as follows:

    int b;
    {
    	b = 13;
    }
    
  2. Do the following in the constructor:

    b = 13;
    

Check https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html to learn more about it.

huangapple
  • 本文由 发表于 2020年8月16日 00:36:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63428421.html
匿名

发表评论

匿名网友

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

确定