What's the access modifier of the default constructor in java? - java

We all know that if we don't specifically define a constructor, the compiler inserts an invisible zero-parameter constructor. I thought its access modifier was public, but in dealing with an inner class issue, I found maybe I was wrong. Here is my code:
public class Outer {
protected class ProtectedInner {
// adding a public constructor will solve the error in SubOuterInAnotherPackage class
//public ProtectedInner() {}
}
}
And there is a subclass of Outer in another package:
public class SubOuterInAnotherPackage extends Outer {
public static void main(String[] args) {
SubOuterInAnotherPackage.ProtectedInner protectedInner
= new SubOuterInAnotherPackage().new ProtectedInner(); // Error!! Can't access the default constructor
}
}
You will get an error in the main() method, but if you add a public constructor to the ProtectedInner class, that error is solved. That's why I'm thinking that the modifier of the default constructor is not public! So could anyone tell me what the access modifier of the default constructor is?

I thought its access modifier is public, but when I deal with a inner class issue, I found maybe I was wrong.
Yup. Indeed, I found myself in the same situation a couple of years ago. I was surprised by an error (through Guice injection, which made it slightly harder to find).
The key is to check the spec, in this case section 8.8.9:
In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.
So in this case, your constructor is implicitly protected.

In addition to what Jon pretty well stated, here is an image example, for the visual guys.
If there is no constructor in a class, compiler automatically creates a default constructor.
Here is an example that successfully depicts the above rule:
For further reference, please refer here.

I would like to point out one more thing that I recently got.
If you define a default constructor for your class then it's acess specifier will be what you assign. For example,
public class A{
A(){
// do some stuff
}
}
Here the access specifier of the default constructor is package access and not public access (that of the class).
However
public class A{
// no constructor is defined
}
Here the compiler will sympathize with you and give you a default constructor whose access specifier will be same as the class , that is public.

Related

Is constructor of private inner class also private?

I'm refactoring an android project which is getting to big. Running lint gives me the JSME issue Private member access between outer and inner classes. Considering the following example
public class Outer {
private Inner mInner = new Inner();
private class Inner {}
}
I get the information
Name
private field Inner mInner
Location
class Outer (default package)
Problem synopsis
Access to private member of class 'Inner' at line 2
Problem resolution
Make 'Inner' constructor package-local
Applying the problem resolution changes the source to
public class Outer {
private Inner mInner = new Inner();
private class Inner {
Inner() {}
}
}
I'm a little confused at the moment. Until now I thought the example would be equivalent to
public class Outer {
private Inner mInner = new Inner();
private class Inner {
public Inner() {}
}
}
Am I wrong in this case or is it an issue of lint?
Section 8.8.9 of the Java language specification, "Default constructor" says:
In a class type, if the class is declared public, then the default
constructor is implicitly given the access modifier public (§6.6); if
the class is declared protected, then the default constructor is
implicitly given the access modifier protected (§6.6); if the class is
declared private, then the default constructor is implicitly given the
access modifier private (§6.6); otherwise, the default constructor has
the default access implied by no access modifier.
You're wrong in your understanding, but the linter is not being particularly clear, and the advice probably isn't relevant for Android (which isn't J2ME).
As David explained, the inner class's implicit default constructor has the same access modifier as the class itself, but private members are accessible within the same compilation unit (Java file). There's no language reason to avoid the private constructor.
However, internally, since the classes are compiled into separate output files, the compiler has to create synthetic adapter methods to provide the classes access to the private members. The runtime disadvantage of these methods is irrelevant for desktop applications, but for something as cramped as J2ME, the difference might be worth eliminating by making the member accessible directly (using package scope).
Android performs significant post-processing on the class files, and Android devices are not nearly as constrained as J2ME devices. Unless you're writing code to target both platforms, I'd change the lint configuration.

Preventing object class creation

I've been reading the article about constructors and what have been written there is:
A public class can likewise prevent the creation of instances outside
its package by declaring at least one constructor, to prevent creation
of a default constructor with public access, and by declaring no
constructor that is public.
I'm confused by declaring no constructor that is public. This is because if we don't declare any constructor at all the implicitly-declared default constructor will be implicitly declared with an access modifier of the class. Which means if the class declared as public, the default constructor will be public too. That's we can use it outside the package (create instances outside the package).
You missed this bit:
by declaring at least one constructor
That's what's preventing the default constructor from being created.
The example given has a default access (package access) constructor:
PackageOnly() { }
... so it satisfies both conditions: a) it declares at least one constructor; b) it declares no public constructors.
no, the class can ba public but the constructor can be protected for only package acces or it also can be private - mostly used with factory static method

Why can't constructors be final, static, or abstract?

Why can't constructors be final, static, or abstract in Java?
For instance, can you explain to me why this is not valid?
public class K {
abstract public K() {
// ...
}
}
When you set a method as final it means: "I don't want any class override it." But according to the Java Language Specification:
JLS 8.8 - "Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."
When you set a method as abstract it means: "This method doesn't have a body and it should be implemented in a child class." But the constructor is called implicitly when the new keyword is used so it can't lack a body.
When you set a method as static it means: "This method belongs to the class, not a particular object." But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
The question really is why you want constructor to be static or abstract or final.
Constructors aren't inherited so can't be overridden so whats the use
to have final constructor
Constructor is called automatically when an instance of the class is
created, it has access to instance fields of the class. What will be
the use of a static constructor.
Constructor can't be overridden so what will you do with an abstract
constructor.
A Java constructor is implicitly final, the static / non-static aspects of its semantics are implicit1, and it is meaningless for a Java constructor to be abstract.
This means that the final and static modifiers would be redundant, and the abstract keyword would have no meaning at all.
Naturally, the Java designers didn't see in any point in allowing redundant and/or meaningless access modifiers on constructors ... so these are not allowed by the Java grammar.
Aside: It is a shame that they didn't make the same design call for interface methods where the public and abstract modifiers are also redundant, but allowed anyway. Perhaps there is some (ancient) historical reason for this. But either way, it cannot be fixed without rendering (probably) millions of existing Java programs uncompilable.
1 - Actually, constructors have a mixture of static and non-static semantics. You can't "call" a constructor on an instance, and it they are not inherited, or overridable. This is similar to the way static methods work. On the other hand, the body of a constructor can refer to this, and call instance methods ... like an instance method. And then there is constructor chaining, which is unique to constructors. But the real point is that these semantics are fixed, and there is no point allowing a redundant and probably confusing static modifier.
public constructor: Objects can be created anywhere.
default constructor: Objects can be created only in the same package.
protected constructor: Objects can be created by classes outside the package only if it's a subclass.
private constructor: Object can only be created inside the class (e.g., when implementing a singleton).
The static, final and abstract keywords are not meaningful for a constructor because:
static members belong to a class, but the constructor is needed to create an object.
An abstract class is a partially implemented class, which contains abstract methods to be implemented in child class.
final restricts modification: variables become constant, methods can't be overridden, and classes can't be inherited.
Final: Because you can't overwrite/extend a constructor anyway. You can extend a class (to prevent that you make it final) or overwrite a method (to prevent that you make it final), but there is nothing like this for constructors.
Static: If you look at the execution a constructor is not static (it can access instance fields), if you look at the caller side it is (kind of) static (you call it without having an instance. Its hard to imagine a constructor being completely static or not static and without having a semantic separation between those two things it doesn't make sense to distinguish them with a modifier.
Abstract: Abstract makes only sense in the presence of overwriting/extension, so the same argument as for 'final' applies
No Constructors can NEVER be declared as final. Your compiler will always give an error of the type "modifier final not allowed"
Final, when applied to methods, means that the method cannot be overridden in a subclass.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
No Constructors can NEVER be declared final. YOur compiler will always give an error of the type "modifer final not allowed"
Check the JLS Section 8.8.3 (The JLS & API docs should be some of your primary sources of information).
JLS section 8 mentions this.
Constructors (§8.8) are similar to methods, but cannot be invoked
directly by a method call; they are used to initialize new class
instances. Like methods, they may be overloaded (§8.8.8).
But constructors per say are not regular methods. They can't be compared as such.
why constructor can not be static and final are well defined in above answers.
Abstract: "Abstract" means no implementation . and it can only be implemented via inheritance. So when we extends some class, all of parent class members are inherited in sub-class(child class) except "Constructor". So, lets suppose, you some how manage to declare constructor "Abstract", than how can you give its implementation in sub class, when constructor does not get inherit in child-class?
that's why constructor can't be
abstract .
lets see first
final public K(){
*above the modifier final is restrict 'cause if it final then some situation where in some other class or same class only we will override it so thats not gonna happen here proximately not final
eg:
we want public void(int i,String name){
//this code not allowed
let static,, static itz all about class level but we create the object based constructor by using 'new' keyword so,,,,,, thatsall
abstract itz worst about here not at 'cause not have any abstract method or any declared method
Unfortunately in PHP the compiler does not raise any issue for both abstract and final constructor.
<?php
abstract class AbstractClass
{
public abstract function __construct();
}
class NormalClass
{
public final function __construct() {
echo "Final constructor in a normal class!";
}
}
In PHP static constructor is not allowed and will raise fatal exception.
Here in AbstractClass obviously a constructor either can be declared as abstract plus not implemented or it can be declared as something among (final, public, private, protected) plus a function body.
Some other related facts on PHP:
In PHP having multiple constructor __construct() is not possible.
In PHP a constructor __construct() can be declared as abstract, final, public, private and protected!
This code was tested and stood true for in PHP versions from 5.6 up to 7.4!

In Java, what happens when you have a method with an unspecified visibility keyword?

I have been working with android for a few years now, not once have I had a teacher or anyone to tell me what to do.
This whole time I have wondered to myself this.
When you have a method I generally see...
public void method(){
//Stuff
}
or
private void method(){
//stuff
}
I know that a void is a method with no return value, and that public is the visibility of the method in a way but would it matter if I just used something like this...
void method(){
//stuff
}
Because then the methods visibility would just be default anyway?
I have no idea if I am right or not, is it just good practice to specify "public" or "private" ?
Not specifying anything has a specific meaning:
public - any class can access this member
protected - subclasses can access this member (as well as code in the same class or in the same package)
private - only code in the same class can access this member
nothing ("default" access) - only code in the same package can access this member
Arguably the last case should have had its own keyword, but we're stuck with it now. Unless you really mean to use default visibility, it's poor form to not specify anything - did you really need package visibility for some reason, or did you just default to package visibility for everything? Best practice is to explicitly use private for non-public members unless you need one of the others.
Java has four levels of visibility: public, protected, (default), private
Visible to the package. the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Default Access Modifier - No keyword:
Default access modifier means we do not explicitly declare an access
modifier for a class, field, method etc.
A variable or method declared without any access control modifier is
available to any other class in the same package. The default modifier
cannot be used for methods, fields in an interface.
Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only
be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class
and interfaces cannot be private.
Variables that are declared private can be accessed outside the class
if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates
itself and hide data from the outside world.
Public Access Modifier - public:
A class, method, constructor, interface etc declared public can be
accessed from any other class. Therefore fields, methods, blocks
declared inside a public class can be accessed from any class
belonging to the Java Universe.
However if the public class we are trying to access is in a different
package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a
class are inherited by its subclasses.
Protected Access Modifier - protected:
Variables, methods and constructors which are declared protected in a
superclass can be accessed only by the subclasses in other package or
any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however methods
and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method
or variable, while preventing a nonrelated class from trying to use
it.
Java has four levels of visibility: public, protected, (default), private. The meaning of these is as follows:
public - makes your methods accessible to any other class.
protected - makes your methods accessible to any class in the same package OR any subclass of your class.
(default, i.e. no modifier) - makes your methods accessible only to classes in the same package.
private - makes your methods accessible only to the current class.
The same rules apply when specifying the access modifiers on classes, methods and fields.

How can a Java class have no no-arg constructor?

The Oracle Java tutorial site has this paragraph that is confusing me:
All classes have at least one
constructor. If a class does not
explicitly declare any, the Java
compiler automatically provides a
no-argument constructor, called the
default constructor. This default
constructor calls the class parent's
no-argument constructor, or the Object
constructor if the class has no other
parent. If the parent has no
constructor (Object does have one),
the compiler will reject the program.
If all objects directly or indirectly inherit from Object how is it possible to elicit the compiler rejection spoken of? Does it have to do with the constructor being private?
If all objects directly or indirectly inherit from Object how is it possible to elicit the compiler rejection spoken of?
I think the basis is of your misunderstanding is that you are thinking that constructors are inherited. In fact, constructors are NOT inherited in Java. So consider the following example:
public class A {
public A(int i) { super(); ... }
}
public class B extends A {
public B() { super(); ... }
}
The class A:
does not inherit any constructors from Object,
does not explicitly declare a no-args constructor (i.e. public A() {...}), and
does not have a default constructor (since it does declare another constructor).
Hence, it has one and only one constructor: public A(int).
The call to super() in the B class tries to use a non-existent no-args constructor in A and gives a compilation error. To fix this, you either need to change the B constructor to use the A(int) constructor, or declare an explicit no-args constructor in A.
(Incidentally, it is not necessary for a constructor to explicitly call a superclass constructor ... as I've done. But a lot of people think it is good style to include an explicit call. If you leave it out, the Java compiler inserts an implicit call to the superclasses no-args constructor ... and that results in a compilation error if the no-args constructor does not exist or is not visible to the subclass.)
Does it have to do with the constructor being private?
Not directly. However, declaring a constructor private will prevent that constructor being called from a child class.
The key thing to understand is that the no-arg constructor will only be automatically generated if the class doesn't already have a constructor.
It's thus easy to create a class that doesn't have a no-arg constructor.
The simplest way to think of this problem is as follows:
The non-args constructor is provided as the default constructor by Java for any class you create.
The moment you create a custom constructor with arguments, Java says “hey, this class has got a custom constructor, so I am not going to bother creating/supplying the default non-args constructor!”
As a result now your class does NOT has the default non-args constructor.
This means when you create a subclass, based on your class, you need explicitly call the arguments based custom constructor that you created.
If you have a sub-class of a sub-class
class A
{
A(int i) {..}
}
class B extends A
{
}
Here the default constructor inserted into B will try to invoke A's no-argument constructor (which doesn't exist) as it only has a constructor taking one argument
The immediate superclass of the object must have a protected or public constructor (or no constructor at all, in which case one will be created). So, if I create a class that extends Object, with a private constructor only, then nothing will be able to extend my class.
Yes. A private contructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
The declaration of a private constructor prevents the automatic generation of a default constructor.
EDIT:
A class defined within another class
is called a nested class. Like other
members of a class, a nested class can
be declared static or not. A
nonstatic nested class is called an
inner class. An instance of an inner
class can exist only within an
instance of its enclosing class and
has access to its enclosing class's
members even if they are declared
private.
What this means is that if you inherit from a line of class(es) that make the default no-arg constructor private (or it does not exist, for example), your sub-classes must declare a constructor in line with its parent's alternative constructor.
For example, the following declaration of Bar is not allowed:
public class Foo {
private Foo() { } // or this doesn't even exist
public Foo(int i) {
}
}
public class Bar extends Foo {
}
Let me append to all aforementioned one more interesting case where the default/no-arg constructor is infeasible, in the sense that unless it is explicitly declared, the compiler cannot assume it and yet it has nothing to do with subclassing. This is the case of having a class with a final field which expects a constructor to initialize it. For example:
class Foo extends Object {
private final Object o;
public Foo(Object o){
this.o = o;
}
}
Here it's easy to see that an instantiation of a Foo-object requires the initialization of the final field o so any invocation of Foo() - directly or not - is doomed to failure... Let me underline that the no-arg constructor in the super class (Object) exists and is publicly accessible but it is the presence of the final field (o) that deactivates it in Foo.

Categories