Hello, I encountered a problem of the following kind: there is a public class. When trying to create a descendant with a modifier other than public writes

"modifier ... not allowed here".

I read on the Internet and found that the class heir can have the same access level or “wider” than the parent. When creating a third class that is not someone's heir, writes

"modifier ... not allowed here"

with private . With the public modifier it is clear (there can be only one private in one java file), I don’t need a protected one - there will be no heirs. All classes are in the same file and one file (the program is educational and small). There is no problem only with the package modifier.

Explain, please, what is wrong.

 package Animals; public class Bird { public static void main(String[] args) { } } class Parrot extends Bird { } private class Cat { } 
  • You would have led the code. - Vartlok
  • vote for closing a question due to insufficient details - Roman C
  • Now add the code - Muscled Boy

1 answer 1

See it. In this form, the private or protected classes Parrot and Cat would not be available to anyone, not even the main method in the Bird class.

Without specifying a specific modifier, classes will have package-visibility, that is, visible to everyone within the package of Animals (by the way, packages are named with a small letter).

For internal classes, the task of visibility already makes sense: they can be parts of the implementation of an external class that you don’t need to know about the world. Those. such code will compile:

 public class Bird { private class Cat { } public static void main(String[] args) { } } 

This technique is widely used in classes included in the JDK. For example, the LinkedList list does not show the implementation detail — the LinkedList.Node list node class; therefore, it declares it like this:

 public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable { private static class Node<E> { ... } } 
  • That is, in my case, use inner - the class is not worth it? Is it more expedient to create them with a package - visibility? And tell me, please, why in case I make bird protected knocks an error? - Muscled Boy
  • There should be one public class in the file - Nofate ♦
  • is this a prerequisite? - Muscled Boy
  • I understand, the question may seem stupid, but still risk to ask you when it is really worth using internal and nested classes? - Muscled Boy
  • if you create a bird package class, just like parrot, then the program will work, it means you don’t have to create at least one public, but if I created it, it would be one, did that mean? - Muscled Boy