declare java class as private trigger compilation error - java

According to java tutorial https://docs.oracle.com/javase/tutorial/java/javaOO/classdecl.html
You can also add modifiers like public or private at the very
beginning—so you can see that the opening line of a class declaration
can become quite complicated. The modifiers public and private, which
determine what other classes can access MyClass, are discussed later
in this lesson. The lesson on interfaces and inheritance will explain
how and why you would use the extends and implements keywords in a
class declaration. For the moment you do not need to worry about these
extra complications.
In general, class declarations can include these components, in order:
Modifiers such as public, private, and a number of others that you will encounter later.
The class name, with the initial letter capitalized by convention.
The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more
than one interface.
The class body, surrounded by braces, {}.
But the compiler complain with a message Modifier 'private' not allowed here when declare a class (top level class) with private modifier.
this is my code
private class MyPrivateClass {
}
and the error message in compilation
1: error: modifier private not allowed here

From section 8.1.1 of the Java Language Specification (JLS):
The access modifiers protected and private pertain only to member classes within a directly enclosing class or enum declaration.
In other words, a private class is only allowed if it is enclosed within another class.

Related

Defining a class inside a method of another class

I have a class A. I define another class B within a method (even main) of the class A and class B can access all the variables within the scope of the method it is defined in. What is the terminology for such classes (as B)? Some people have been saying Nested classes or Inner classes but IIRC, those are the classes where they have another class as their data members (kinda like composition in C++).
The second part of my question is that some people have been saying that when you have a class defined within a method of another class, then the variables of the first class (A) that are accessed by the later class (B) need to be declared final. Is this to be followed strictly and why so?
According to the Java Language Specification these are "local classes":
A local class is a nested class (§8 (Classes)) that is not a member of
any class and that has a name (§6.2, §6.7).
or "anonymous [inner] classes", which are just the ones that don't have a name (e.g. Interface x = new Interface() { ...).
These are special cases of inner classes which is generally what I've heard people refer to them as.
As for your second question, "Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted." So it is a compile-time error if you try to access non-final local variables. Obviously this part must be followed strictly if you want your class to compile.
I have not personally heard the advice that you should not access non-final fields of the enclosing class, and I'm pretty sure it's allowed. While arguments could be made that fields should be final unless they can't be, I don't see any stylistic reason this should be more important in inner classes. There is a technical difference that accessing a field from an inner class may cause the compiler to create and call synthetic getters and setters, but this is generally a minor performance concern.

what is the need of multiple class modifiers in java?

While reading oracles Java documentation(chapter 8) I came across this interesting piece of line:
"If two or more (distinct) class modifiers appear in a class declaration, then it is customary, though not required, that they appear in the order consistent with that shown above in the production for ClassModifier."
and here is the Class Modifiers
ClassModifiers:
ClassModifier
ClassModifiers ClassModifier
ClassModifier: one of
Annotation public protected private
abstract static final strictfp
My question is what is the need for multiple class modifiers? when we can make use of multiple class modifiers?
Well, you can have a public abstract static strictfp inner class; each one of those is orthogonal to the rest. In general, you can group them in the following way:
public/protected/private: access modifiers - determining who has access to the class literal.
abstract/final: inheritance modifiers
static: only for inner classes
strictfp: it's orthogonal to everything else.
Two examples:
public final class MyClass { }
protected abstract class MyClass {}
Simply, to create a class that has the features dictated by several modifiers. Not all the modifiers are mutually exclusive. For example, abstract disallows making instances of the class, and public makes the class accessible even outside its package. Hence, to make an abstract class that's accessible outside its own package, you'd need to make it public abstract class.

The use of visibility modifiers in Java

class Orange{
Orange(){
}
}
What is the difference between the usage of the modifier - in this case, package-private - in front of the class and in front of the constructor? I think the modifier in front of the constructor means it is allowed to instantiate an instance of the class Orange. But what about the modifier in front of the class?
To start with there are 4 access levels created by 3 access modifiers.
public - accessible everywhere
protected - accessible in the same package and in the children
default - accessible only in the same package
private - accessible only in the same class.
You are correct about - Modifiers at the level of constructors are directly related to the instantiation of the class.
Modifiers at the level of Class decide the accessibility of the Class.
First, to assuage any fears, the code you've provided is perfectly valid Java syntax.
In effect, you've created a class that can only be instantiated/used by other classes in the default package. It would also work if you defined it in a package (e.g. package foo;) since only the classes in package foo could see this class).
Now, to the crux of the question.
There are different ways to control access to fields and members. and they each do different things.
private visibility is the least visible. Only the defining class can access the field.
No modifier, or package private is the second least visible. The defining class and all classes within the package may access the field, but subclasses and the rest of the world cannot.
protected is the second most visible. Only other classes are prohibited from accessing the field.
public is the most visible. Everything can access the field.
Modifiers at the level of the class get interesting. This comes from the Java Language Specification, §8.1.1:
The access modifier public (§6.6) pertains only to top level classes
(§7.6) and to member classes (§8.5), not to local classes (§14.3) or
anonymous classes (§15.9.5).
The access modifiers protected and private (§6.6) pertain only to
member classes within a directly enclosing class or enum declaration
(§8.5).
The modifier static pertains only to member classes (§8.5.1), not to
top level or local or anonymous classes.
It is a compile-time error if the same modifier appears more than once
in a class declaration.
If two or more (distinct) class modifiers appear in a class
declaration, then it is customary, though not required, that they
appear in the order consistent with that shown above in the production
for ClassModifier.
In general, a class declaration appears something like this:
ClassDeclaration:
NormalClassDeclaration
EnumDeclaration
NormalClassDeclaration:
ClassModifiers(opt) class Identifier TypeParameters(opt)
Super(opt) Interfaces(opt) ClassBody
Anything with (opt) is considered optional.
So, what does this pare down to?
The JLS mandates that a class does not need a [class] modifier.
The JLS mandates that, if a [class] modifier is present, then it follows one of these rules:
If the modifier is public, then it is only applicable to top level classes and member classes.
If the modifier is protected or private, then it is only applicable to member classes within a directly enclosing class or enumeration.
The static modifier may appear, but is only applicable to member classes.
Constructors have a similar rule set.
ConstructorDeclaration:
ConstructorModifiers(opt) ConstructorDeclarator
Throws(opt) ConstructorBody
ConstructorDeclarator:
TypeParameters(opt) SimpleTypeName ( FormalParameterList(opt) )
Again, this breaks down to:
The JLS mandates that a constructor does not need a [constructor] modifier.
The JLS mandates that a constructor modifier cannot contain abstract, static, final, native, strictfp, or synchronized.
The JLS mandates, if no access modifier is specified for the constructor of a normal class, the constructor has default access (§8.8.3, emphasis mine).
You can only declare a public or default class (in case of top level classes only) in Java and these modifiers decide the accessiblity of the class.
I also suggest you to see "Why can't a class or an interface receive private or protected access modifiers?"
Now as for as constructor concerns, a constructor will have aaccess-control of type default when no access-modifier is defined explicitly. So this constructor will have a Package Level Access. Only those class which are defined within that package as that of the class with this default constructor will be able to access it. See "Aren't Java constructors public by default?"
If the constructor is made private, then only the code within that class can access this.
For a better understanding of modifiers, you need to see "Access Modifiers In Java"
Modifier of class defines who can access the class. For example public class can be accessed by classes from any package, if no modifier is written the class can be accessed by classes from the same package only.
Modifier of constructor, method and field has the same meaning. However private and protected have more sense. Private can be accessed from the current class only. Protected from its subclasses as far as from just classes from the same package.
Concerning to your question about constructor. Class can have several constructors. Some of them can be private, some other public. You are right that there is no sense to make constructor public if class is package protected: no-one outside package can call this class anyway.
This is exactly like writing public constructors for abstract classes. Since abstract class cannot be instantiated itself its constructors should be protected or private although compiler does not care about this.
BTW using default package is not commonly used and not recommended technique.
The use and types of class level modifiers:
http://javapapers.com/core-java/access-modifiers-in-java-explain/
The use and types of constructor level modifiers:
http://www.careercup.com/question?id=296844#commentThread302715
Class modifiers work similarly to method modifiers. Public, private, final, abstract, etc. work.
Public allows the class and its methods to be accessed by classes from any package.
No modifier only allows classes to be access from it's defined package.
Private would prevent all access (no point to this if using with a top-level class).
Abstract classes allow you to create child classes derived from the parent (abstract) class. For example, you can make an Abstract Shape class and have a Rectangle class extend shape, inheriting all its methods, variables, and forcing it to define any abstract methods.
Access Modifiers:
Public - {Can access anywhere in the project}
Private - {Can access only inside the class}
Protected - {Can access within the package and sub classes}
Default - {can access within the package}
Non-Access Modifiers:
Static - {for creating class variable and method}
Final - {for creating finalized variable and method}
Abstract - {for creating abstract method and class}
Synchronized - {for threads}
Some brief discussion on the above modifiers in this link. Refer it for the better understanding.
I find the best visibility level in Java to be the default visibility i.e. package visibility, because it enables unit test classes to access all the methods, if the test is placed in the same package as the main class.
Also package visibility is shorter to write since you can omit the visibility declaration, so there is less boiler plate.
The second best visibility level is protected, since in some cases you can create your test classes as sub-classes of your main class. However, as stated before, package visibility works better in most cases, if you use packages properly.
Third, typically if you run Sonar and do code review and static analysis on large projects, I have found out that typically 80% of the methods are public, and 20% are private/protected. Thus, the main idea of using private or protected methods is to protect the data/properties from being accessed by bypassing the accessors. Most of the methods will be typically public anyways.
The most useless visibility level (but unfortunately commonly used) is private as it's impossible to test (without using Reflection and modifying the visibility to something else). Also, private prohibits code re-use in sub-classes, which is the main idea of using object oriented paradigm in the first place, and thus should be avoided. For the same reasons keyword final should be avoided in most cases.
Thus, I find your example to be the best practice how to define the visibility levels, except that your constructor is not public :). However, you are missing the package declaration and unit tests.

What is the default access specifier in Java?

I just started reading a Java book and wondered; which access specifier is the default one, if none is specified?
The default visibility is known as “package-private” (though you can't use this explicitly), which means the field will be accessible from inside the same package to which the class belongs.
As mdma pointed out, it isn't true for interface members though, for which the default is "public".
See Java's Access Specifiers
The default specifier depends upon context.
For classes, and interface declarations, the default is package private. This falls between protected and private, allowing only classes in the same package access. (protected is like this, but also allowing access to subclasses outside of the package.)
class MyClass // package private
{
int field; // package private field
void calc() { // package private method
}
}
For interface members (fields and methods), the default access is public. But note that the interface declaration itself defaults to package private.
interface MyInterface // package private
{
int field1; // static final public
void method1(); // public abstract
}
If we then have the declaration
public interface MyInterface2 extends MyInterface
{
}
Classes using MyInterface2 can then see field1 and method1 from the super interface, because they are public, even though they cannot see the declaration of MyInterface itself.
If no access specifier is given, it's package-level access (there is no explicit specifier for this) for classes and class members. Interface methods are implicitly public.
The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.
Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package
It depends on what the thing is.
Top-level types (that is, classes, enums, interfaces, and annotation types not declared inside another type) are package-private by default. (JLS §6.6.1)
In classes, all members (that means fields, methods, and nested type declarations) and constructors are package-private by default. (JLS §6.6.1)
When a class has no explicitly declared constructor, the compiler inserts a default zero-argument constructor which has the same access specifier as the class. (JLS §8.8.9) The default constructor is commonly misstated as always being public, but in rare cases that's not equivalent.
In enums, constructors are private by default. Indeed, enum contructors must be private, and it is an error to specify them as public or protected. Enum constants are always public, and do not permit any access specifier. Other members of enums are package-private by default. (JLS §8.9)
In interfaces and annotation types, all members (again, that means fields, methods, and nested type declarations) are public by default. Indeed, members of interfaces and annotation types must be public, and it is an error to specify them as private or protected. (JLS §9.3 to 9.5)
Local classes are named classes declared inside a method, constructor, or initializer block. They are scoped to the {..} block in which they are declared and do not permit any access specifier. (JLS §14.3) Using reflection, you can instantiate local classes from elsewhere, and they are package-private, although I'm not sure if that detail is in the JLS.
Anonymous classes are custom classes created with new which specify a class body directly in the expression. (JLS §15.9.5) Their syntax does not permit any access specifier. Using reflection, you can instantiate anonymous classes from elsewhere, and both they and their generated constructors are are package-private, although I'm not sure if that detail is in the JLS.
Instance and static initializer blocks do not have access specifiers at the language level (JLS §8.6 & 8.7), but static initializer blocks are implemented as a method named <clinit> (JVMS §2.9), so the method must, internally, have some access specifier. I examined classes compiled by javac and by Eclipse's compiler using a hex editor and found that both generate the method as package-private. However, you can't call <clinit>() within the language because the < and > characters are invalid in a method name, and the reflection methods are hardwired to deny its existence, so effectively its access specifier is no access. The method can only be called by the VM, during class initialization. Instance initializer blocks are not compiled as separate methods; their code is copied into each constructor, so they can't be accessed individually, even by reflection.
default is a keyword that is used as an access modifier for methods and variables.
Using this access modifier will make your class, variable, method or constructor acessible from own class or package, it will be also is set if no access modifier is present.
Access Levels
Modifier Class Package Subclass EveryWhere
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N
if you use a default in a interface you will be able to implement a method there like this exemple
public interface Computer {
default void Start() {
throw new UnsupportedOperationException("Error");
}
}
However it will only works from the 8 Java version
Official Documentation
Access Modifiers in Java
See here for more details. The default is none of private/public/protected, but a completely different access specification. It's not widely used, and I prefer to be much more specific in my access definitions.
the default access specifier is package.Classes can access the members of other classes in the same package.but outside the package it appears as private
Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:
Bill Venners: Java has four access levels. The default is package. I
have always wondered if making package access default was convenient
because the three keywords that people from C++ already knew about
were private, protected, and public. Or if you had some particular
reason that you felt package access should be the default.
James Gosling: A package is generally a set of things that are kind of
written together. So generically I could have done one of two things.
One was force you always to put in a keyword that gives you the
domain. Or I could have had a default value. And then the question is,
what makes a sensible default? And I tend to go for what is the least
dangerous thing.
So public would have been a really bad thing to make the default.
Private would probably have been a bad thing to make a default, if
only because people actually don't write private methods that often.
And same thing with protected. And in looking at a bunch of code that
I had, I decided that the most common thing that was reasonably safe
was in the package. And C++ didn't have a keyword for that, because
they didn't have a notion of packages.
But I liked it rather than the friends notion, because with friends
you kind of have to enumerate who all of your friends are, and so if
you add a new class to a package, then you generally end up having to
go to all of the classes in that package and update their friends,
which I had always found to be a complete pain in the butt.
But the friends list itself causes sort of a versioning problem. And
so there was this notion of a friendly class. And the nice thing that
I was making that the default -- I'll solve the problem so what should
the keyword be?
For a while there actually was a friendly keyword. But because all the
others start with "P," it was "phriendly" with a "PH." But that was
only in there for maybe a day.
http://www.artima.com/intv/gosling2P.html
Update Java 8 usage of default keyword:
As many others have noted The default visibility (no keyword)
the field will be accessible from inside the same package to which the
class belongs.
Not to be confused with the new Java 8 feature (Default Methods) that allows an interface to provide an implementation when its labeled with the default keyword.
See: Access modifiers
There is an access modifier called "default" in JAVA, which allows direct instance creation of that entity only within that package.
Here is a useful link:
Java Access Modifiers/Specifiers
First of all let me say one thing there is no such term as "Access specifier" in java. We should call everything as "Modifiers". As we know that final, static, synchronised, volatile.... are called as modifiers, even Public, private, protected, default, abstract should also be called as modifiers . Default is such a modifiers where physical existence is not there but no modifiers is placed then it should be treated as default modifiers.
To justify this take one example:
public class Simple{  
    public static void main(String args[]){  
     System.out.println("Hello Java");  
    }  
}  
Output will be: Hello Java
Now change public to private and see what compiler error you get:
It says "Modifier private is not allowed here"
What conclusion is someone can be wrong or some tutorial can be wrong but compiler cannot be wrong.
So we can say there is no term access specifier in java everything is modifiers.

Why can't we define a top level class as private?

Why does Java not allow a top level class to be declared as private? Is there any other reason other than "We can't access a private class"?
A top-level class as private would be completely useless because nothing would have access to it.
Java doesn’t allow a top level class to be private. Only 'public' or 'package'.
I believe a better question would be:
What would it mean for a top level class to be private?
If you think in terms of access levels, the level above class is package. In fact you can have package private top level classes in Java! Taking from the Oracle (formerly Sun) Java tutorials:
If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)
Depending on the answer to the question I asked, this might fit with your definition of a "top level private class".
Private classes are allowed, but only as inner or nested classes. If you have a private inner or nested class, then access is restricted to the scope of that outer class.
If you have a private class on its own as a top-level class, then you can't get access to it from anywhere. So it does not make sense to have a top level private class.
In theory, you could instantiate and call methods on a private top-level class (if such a thing were allowed by the language ... which it isn't!), but you would have to use reflection to do this. Sensibly (IMO) Sun decided that private top-level classes were not a good thing to support at the language level.
Actually, it is possible that the JVM might support top-level private "classes" created by bytecode magic. But it is not a useful thing to do.
UPDATE - In fact, the current JVM spec makes it clear that the ACC_PRIVATE bit of the access flags word for a class is "reserved for future use", and that Java implementations should treat it as unset. Thus, the above speculation is moot for any JVM that strictly implements the current specification.
We can not declare an outer class as private. More precisely, we can not use the private access specifier with an outer class. As soon as you try to use the private access specifier with a class you will get a message in Eclipse as the error that only public, final, and abstract can be used as an access modifier with a class.
Making a class private does not make any sense as we can not access the code of its class from the outside.
There would be no way to access that class or its members.
This needs a simple understanding of why it is not required to declare classes as private in Java.
If your class is itself a standalone program/software (which is highly unlikely) then you would have already defined it in a project and a package specific for it. So adding the private keyword is redundant to it.
If that's not the case then default access is then it means your program/software depends on different classes to run. If we are declaring one class among them as private (in case if we could) then we are restricting its accessibility by other classes, etc. which isn't of any use. It simply means that the class declared as private by us isn't of any use for the code to run. Which again renders it useless.
If you mean package level access then for default access we don't need to declare any keyword before it.
As we already know, a field defined in a class using the private keyword can only be accessible within the same class and is not visible to the outside world.
So what will happen if we will define a class private? Will that class only be accessible within the entity in which it is defined which in our case is its package?
Let’s consider the below example of class A
package com.example;
class A {
private int a = 10;
// We can access a private field by creating object of same class inside the same class
// But really nobody creates an object of a class inside the same class
public void usePrivateField(){
A objA = new A();
System.out.println(objA.a);
}
}
Field ‘a’ is declared as private inside ‘A’ class and because of it, the ‘a’ field becomes private to class ‘A' and can only be accessed within ‘A’. Now let’s assume we are allowed to declare class ‘A’ as private, so in this case class ‘A’ will become private to package ‘com.example’ and will not be accessible from outside of the package.
So defining private access to the class will make it accessible inside the same package which the default keyword already does for us. Therefore there isn't any benefit of defining a class private; it will only make things ambiguous.
You can read more in my article Why an outer Java class can’t be private or protected.
You cannot define a top level class private (or anything else besides public). You will get a compilation error.
Something.java:6: error: modifier private not allowed here
private class Something {
^
1 error
You have only two options, public or no access modifier at all. By omitting public you, implicitly, limit class access to within the package (aka: package-private).

Categories