Java中的本地范围 [英] local scope in Java

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

问题描述

为什么花括号没有在Java中定义单独的本地作用域?我期望这是主要花括号语言(C,C ++,Java,C#)所共有的功能.

Why is it that curly braces do not define a separate local scope in Java? I was expecting this to be a feature common to the main curly brace languages (C, C++, Java, C#).

class LocalScopeTester
{
    public static void main(String... args)
    {
        Dog mine = new Dog("fido");
        if (mine.getName().equals("ace"))
        {
            Dog mine = new Dog("spot"); // error: duplicate local
        }
        else
        {
            Dog mine = new Dog("barkley"); // error: duplicate local
            {
                Dog mine = new Dog("boy"); // error: duplicate local
            }
        }
    }
}

推荐答案

它们确实定义了单独的局部作用域,但是您仍然不能从父作用域中屏蔽局部变量(但是您当然可以屏蔽实例变量).

They do define a separate local scope, but you still cannot mask local variables from a parent scope (but you can of course mask instance variables).

但是您可以定义新变量(使用不同的名称),并且它们的范围将限于括号内.

But you can define new variables (with different names) and their scope will be limited to within the braces.

这篇关于Java中的本地范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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