Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private class declaration [duplicate]

Possible Duplicate:
Java: Why can we define a top level class as private?

Why can't we declare a private outer class? If we can have inner private class then why can't we have outer private class...?

like image 471
T__ Avatar asked Feb 04 '13 18:02

T__


People also ask

What happens when we declare class as private?

It is only applicable to constructor, methods, and fields inside the classes. If a variable or methods or constructor is declared as private then we can access them only from within the class i.e from outside the class we can't access them.

Can you declare a private class?

No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier).

Why we cant declare class as private?

A top-level class as private would be completely useless because nothing would have access to it. If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here" . This means that a top level class cannot be private.

Can we declare private class inside main class?

Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method.


2 Answers

Private outer class would be useless as nothing can access it.

See more details:

Java: Why can we define a top level class as private?

like image 148
Amit Avatar answered Sep 30 '22 03:09

Amit


private modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public, abstract & final are permitted.

Note : Even you can not make it protected.

like image 21
Subhrajyoti Majumder Avatar answered Sep 30 '22 03:09

Subhrajyoti Majumder