具有相同名称但不同类型的变量 [英] Variables having same name but different type

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

问题描述

我已阅读此处,在Java中可能有两个变量相同名称但不同类型在同一范围内共存。我的意思是这个

 类测试
{
private int x;
private double x;
}

但是所有java IDE都不允许这样的代码。我想知道这样的代码是否真的在语法上是正确的,或者只是IDE不允许这样的代码来防止歧义。



无论如何这里是网站


如果你很幸运,你可能可以重新编译来自Jad的输出。但是,Java VM对变量命名的规则比Java语言本身更宽松。例如,有效的类文件可以有几个名为'a'的变量,只要它们有不同的类型。如果你反编译这样的类,你获得的源代码将无效。



JAD通常会重命名有问题的字段,并制作一个可重新编译的文件......唯一的问题是重新编译的文件与原始类不兼容。



解决方案

你不能拥有同名的变量(bu (不同类型)存在于同一范围内。
如果有可能,那么java编译器将如何确定你的意思。



考虑这段代码

  class test 
{
private int x;
private double x;

test()//构造函数
{
System.out.println(x); //错误无法确定你的x是什么意思
}
}

java编译器无法理解您实际指的是哪个x。所以这样的代码在语法上不正确且不可编译。



但是存在诸如 ClassEditor ,它可以在创建后修改生成的类文件。在那里可以将两个变量的名称更改为相同。



但是这样的类不一定是java jvm可以运行的。



你引用的软件即 JAD 可以在类文件中重命名此类重复的命名变量,以便您获得的源代码实际上在语法上是正确的


I have read here that in Java it is possible for two variables having same name but different type to co-exist in the same scope. What I mean is this

class test
{
    private int x;
    private double x;
}

But all java IDE do not allow such code. I want to know whether such a code is really syntactically correct, or simply the IDE do not allow such code to prevent ambiguity.

Anyway here is the extract from the website

"If you're lucky, you might be able to recompile the output from Jad. However, the Java VM has more lenient rules for variable naming than the Java language itself. For instances, a valid class file can have several variables named 'a', as long as they have different types. If you decompile such a class, the source code you get will not be valid.

JAD will usually rename the offending fields, and make a recompilable file... the only problem being that the recompiled file won't be compatible with the original classes."

解决方案

You cannot have variables having same name (but different type) to exist in the same scope. Consider if it was possible then how would the java compiler determine which one you meant.

Consider this code snippet

class test
{
    private int x;
    private double x;

    test() //constructor
    {
        System.out.println(x); //Error cannot determine which x you meant
    } 
}

The java compiler cannot understand which x you are actually referring to. So such a code is not syntactically correct and not compilable.

However there exists tools such as ClassEditor which can modify the generated class file after it is created. There it is possible to change the name two variables to same.

However such a class is not necessarily runnable by the java jvm.

The software which you have quoted i.e JAD can rename such duplicate named variables in the class file so that the source code which you will be getting will actually be syntactically correct

这篇关于具有相同名称但不同类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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