类范围变量与方法范围变量 [英] Class scope variable vs method scope variable

查看:110
本文介绍了类范围变量与方法范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道变量范围由块 {的开头和块的结尾} 包围。如果在块中声明了相同的变量,则会发生编译错误已定义的变量。但请看下面的示例。

I know that variable scope is enclosed by a start of block { and an end of block }. If the same variable is declared within the block, then the compile error Variable already defined occurs. But take a look at following example.

public class Test{
int x=0;// Class scope variable

public void m(){
  int  x=9;   //redeclaration of x is valid within the scope of same x. 

  if(true){
      int x=7; // but this redeclaration generates a compile time error.
  }

}

此处, x 可以在方法中重新声明,尽管它已在类中声明。但是在 if 块中, x 无法重新声明。

Here, x can be redeclared in a method, although it's already declared in the class. But in the if block, x can't be redeclared.

为什么重新声明类范围变量不会产生错误,但方法范围变量重新声明会产生错误?

Why is it that redeclaration of a class scope variable doesn't generate an error, but a method scope variable redeclaration generates an error?

推荐答案

这是因为 int x = 0 不是变量而是实例字段。允许局部变量与字段具有相同的名称。为区分变量和具有相同名称的字段,我们使用前缀作为实例字段或类名称用于类字段。例如。

This is because int x=0 is not a variable but an instance field. Local variables are allowed to have the same names as fields. To distinguish between a variable and a field with the same name we use this prefix for instance fields or class name for class fields. E.g.

int x = this.x

这篇关于类范围变量与方法范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆