Why does the compiler not give error when we have public methods inside default class

StackOverflow https://stackoverflow.com/questions/19372018

  •  30-06-2022
  •  | 
  •  

Pregunta

Why does the JAVA compiler not give error when we have public methods inside default class ?

When we have non public classes (lets say with default access level) and if we have public methods within that class as follows ,

class Main {

    public void doStuff() {

    }
}

then we cannot access above doStuff() method from outside of the same package. But it is legal to have public access modifier for above method deceleration. So what is the purpose of it ?

¿Fue útil?

Solución

Because it's not an error, and because it could be necessary to avoid an error: for example, if it's an implementation of an interface method.

Otros consejos

There is no harm in allowing public access to members of classes with package visibility: there is no contradiction in defining it this way, so the compiler allows it.

However, you are certainly right that making a member of a package-visible class public does not expand its visibility: if the owning class has package visibility, making all its public members package-visible as well is not going to change anything.

Somebody in the same package could instantiate a Main, and pass it to another class as a Object or an Interface. In the former case methods like toString() and equals() must be public, in the latter methods of that Interface must be.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top