我如何修复类“Shape”暴露在其定义的可见性范围之外的警告? (JAVA 17)

问题描述 投票:0回答:1

我在第 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);
}

但我觉得它看起来不太直观。

java function enums warnings visibility
1个回答
0
投票

为什么会出现警告

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
包私有,具体取决于您的意图。

© www.soinside.com 2019 - 2024. All rights reserved.