Search code examples
javafunctionenumswarningsvisibility

How can I fix warning that Class 'Shape' is exposed outside its defined visibility scope?


I made function 'warn' in line 17 whose parameter is enum Shape. Why is it warning about visibility scope and how can I fix it?

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 recommends generate overloaded method with default parameter values like following code.

public static void warn(){
    warn(null);
}

But I think it doesn't look intuitive.


Solution

  • Why is there a warning Class 'Shape' is exposed outside its defined visibility scope?

    Because the enum AreaCalculator.Shape is only visible to classes in the same package, but the method public static void warn(Shape shape) is visible to any class.

    So if we write a class:

    package a;
    
    import b.AreaCalculator;
    
    public class AreaCalculatorClient {
        public static void main(String[] args) {
            AreaCalculator.warn(AreaCalculator.Shape.CIRCLE);
        }
    }
    

    It will fail to compile, because 'b.AreaCalculator.Shape' is not public in 'b.AreaCalculator'. Cannot be accessed from outside package.

    The fix is to with make Shape public or warn package-private, depending on your intent.

    The fix suggested by IntelliJ IDEA is something you might do if you're convinced that you've chosen the correct visibility for Shape, and yet you want to call something like the warn method from arbitrary classes.