-2

It may be a repeated question. But i need a clear answer for this answer. I am so confused.

For EG: I have class to display time.

import java.util.Date;

**public** class DateDisplay {

    public static void main(String[] args) {
        Date today = new Date();
        System.out.println(today);
    }
}

None of the class in the same package is going to extend this class. Why can not i declare a class at private?

Why JAVA is not allowing me to declare a class as private? What is the reason behind this?

My second question is where should i use inner class? What is purpose of inner class?

Sana
  • 15
  • 1
  • 2
    What would you do with a private (top-level) class? it would not be accessible from anywhere. – Danilo May 02 '16 at 10:06
  • As **one** question per question. – T.J. Crowder May 02 '16 at 10:06
  • https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html – d4rty May 02 '16 at 10:06
  • @downvoter: explain please. not for the question atleast reason for vote. – Sana May 02 '16 at 10:07
  • I want to know the reason for this. Just asking why compiler is not allowing us to declare a class as private. – Sana May 02 '16 at 10:08
  • You wouldn't be able to use it anywhere. Having a private top level class makes no sense. – Peter Lawrey May 02 '16 at 10:11
  • You can't have a private top-level class because A) [That's how the language is designed](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.1), and B) It makes no sense, as it would only be accessible via reflection. – T.J. Crowder May 02 '16 at 10:12

2 Answers2

0

To answer the first question: If you want to get this done define a public/protected class with in it a private class. As a result the private class is only accessible within its class.

Example:
public class x
{
  private class y
  {
  }
}

Here class y is only accessible in class x

I guess this also answers your second question, see for more info
https://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

M. Suurland
  • 725
  • 12
  • 31
0

Access modifiers on a class do not only specify where you can extend the class; they also specify where the class can be used.

private means: accessible only inside the class itself. It would not make sense for a top-level class to be private, because that would mean you could not use the class at all - any other classes would't be able to use it.

If you want to make a class inaccessible to classes outside the package, then use the default access level (don't specify an access modifier at all):

// Only accessible within the same package
class DateDisplay {
    // ...
}

Note however, that a class with a main method should be public.

Jesper
  • 202,709
  • 46
  • 318
  • 350