Why can't a class be protected while it can have a default modifier in java

209 Views Asked by At

While the visibilty of a default modifier comes below that of protected in the heirarcy of modifiers, why is it that a class can be made as default but not as protected.

3

There are 3 best solutions below

0
On

I hope you meant top level class(can only be public or default). Otherwise inner classes can have any modifier.

When we say protected it means that it is accessible from all subclasses of the class enclosing the protected entity(Can be a class).

If outermost class is protected then it defines the very definition of protected modifier.

2
On

why is it that a class can be made as default but not as protected?

A more sensible question would be, why does Java tolerate anything but public top-level classes?

The provision to allow package-private top-level classes is already a hack of the earliest versions of Java, improved on and superseded by nested classes, which can be protected if you want.

1
On

class can be protected!. i,e inner class can be protected .

class A{
protected class C{
}
}

Protedted comes into picture when we are talking about inheritance (extends). Thats why we cant have anything outside inheritance context as protected.!