我正在开发一个 Java 项目,我们必须实现凯撒密码。我的所有代码都可以工作,但我正在使用这个技巧,并且我想确保它不会导致未定义的行为。我对Java作用域的理解是,如果我在函数内部声明byte key
,那么所有不使用关键字this对它的引用都将引用局部变量并使用关键字将引用类字段。我已经测试了该程序,它运行良好,但我对奇怪技巧的经验是,它们可能会导致未定义的行为,并且无法始终运行。
Class Cipher {
byte key = -1;
...
String encrypt(String plaintext) {
byte key = this.key;
if(this.key == -1) {
System.out.print("Please enter a key: ");
key = input.nextByte();
}
...
}
}
更新:我忘记提供一些背景信息。构造类时,您可以选择指定 key 或不指定 key ,如果不指定 key ,则每次调用 encrypt() 或 decrypt() 时都会提示您输入 key 。然后在函数内部使用变量键来执行 ROT 移位。
最佳答案
您正在做的是使用局部变量key
遮蔽key
实例变量。这不是 Java 中未定义的行为。 JLS, Section 6.4.1有这样说:
Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.
和
A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occurs throughout the scope of d.
还有
A declaration d of a local variable or exception parameter named n shadows, throughout the scope of d, (a) the declarations of any other fields named n that are in scope at the point where d occurs,
您的代码仍然可以工作,因为您知道如何通过不使用简单的名称来访问实例变量:
this.key
但是像这样隐藏变量是不好的做法。将局部变量命名为其他名称。
关于java - 这会导致 Java 中未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19277749/