类范围变量与方法范围变量

编程入门 行业动态 更新时间:2024-10-26 10:28:42
本文介绍了类范围变量与方法范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

类范围变量与方法范围变量

本文发布于:2023-11-16 07:33:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602267.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!