0

Simple question I hope

Consider 2 the two following files in the same folder:

Shape.java

public abstract interface Shape { 
    public abstract double area();
    public abstract double perimeter();
    public default String getName() {
        return "default";
    }
}

class Square implements Shape {
    public static void visible() {
        System.out.println("Visible");
    }

    public double area() {
        return 0.00;
    }

    public double perimeter() {
        return 0.00;
    }

    public String getName() {
        return "square";
    }
}

class Triangle implements Shape {
    public double area() {
        return 0.00;
    }

    public double perimeter() {
        return 0.00;
    }

    public String getName() {
        return "triangle";
    }
}

App.Java

public class App {
public static void main(String... args) {
    Shape square = new Square();
    Shape circle = new Triangle();
    Square.visible();
    System.out.println(square.getName());
    System.out.println(circle.getName());
}

}

No packages are declared, and the two shape class implementations are not listed as public packages, so why is this compiling? I would have thought that Square and Triangle classes wouldn't be visible to App. If I label them package A and package b, they can't see each other, as expected. Does the compiler consider 2 files in the same folder with no package declaration to be in the same package by default?

Tthis
  • 13
  • 2
  • 5
    If you specify no package, the class belongs to the default package. If you do that twice, both classes are in the default package, which means both classes are in the same package. It is discouraged to use the default package anyway. It basically exists for noobs: "*Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or **when just beginning development**.*" https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.4.2 – Michael Nov 18 '21 at 14:29
  • 1
    `Does the compiler consider 2 files in the same folder with no package declaration to be in the same package by default?` As Michael just explained, yes, that's exactly what the compiler does. – markspace Nov 18 '21 at 14:34

1 Answers1

2

They are all in the same "default" package. No package declaration means to use the default unnamed package.

swpalmer
  • 3,890
  • 2
  • 23
  • 31