How can i fix warning that Class 'Shape' is exposed outside its defined visibility scope? (JAVA 17)

9.9k Views Asked by At

I made function 'warn' in line 17 whose parameter is enum Shape. Why 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 recommend generate overloaded method with default parameter values like following code.

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

But I think it doesn't look intuitive.

2

There are 2 best solutions below

2
tgdavies On BEST ANSWER

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.

0
Reilas On

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

I'm not receiving any warning here, the code compiles.
If I enter any of the values I get an infinite loop.

To resolve this, assign str upon each while-loop iteration.

String str;

while (!(str = scanner.nextLine()).equals("quit")){
    str = str.toUpperCase();
    warn(Shape.valueOf(str));
}

Output

TRIANGLE
TRIANGLE
RECTANGLE
RECTANGLE
CIRCLE
CIRCLE
quit