我在第 17 行创建了函数“warn”,其参数是枚举 Shape。 为什么会发出有关可见性范围的警告以及如何修复它?
import java.util.Scanner;
public class AreaCalculator {
enum Shape {TRIANGLE, RECTANGLE, CIRCLE}
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String str = scanner.next();
while (!str.equals("quit")){
str = str.toUpperCase();
warn(Shape.valueof(str));
}
}
public static void warn(Shape shape) { //warning
}
Intellij 建议生成具有默认参数值的重载方法,如以下代码。
public static void warn(){
warn(null);
}
但我觉得它看起来不太直观。
为什么会出现警告
Class 'Shape' is exposed outside its defined visibility scope
?
因为
enum
AreaCalculator.Shape
仅对同一个包中的类可见,但方法 public static void warn(Shape shape)
对任何类都可见。
所以如果我们写一个类:
package a;
import b.AreaCalculator;
public class AreaCalculatorClient {
public static void main(String[] args) {
AreaCalculator.warn(AreaCalculator.Shape.CIRCLE);
}
}
它将无法编译,因为
'b.AreaCalculator.Shape' is not public in 'b.AreaCalculator'. Cannot be accessed from outside package
。
修复方法是使
Shape
公开或 warn
包私有,具体取决于您的意图。