EugeneP
EugeneP

Reputation: 12003

Constructor's Private scope

Given this code snippet, could you explain why it woks?

The thing is that the class constructor is marked private, so should not it prevent us to call it with new operator?

public class Alpha {
 protected Alpha() {}
}
class SubAlpha extends Alpha {
 private SubAlpha() {System.out.println("ok");}
 public static void main(String args[]) {
  new SubAlpha();
 }
}

It all works because the static method is part of the class and it can see all private fields and methods, right? Outside this "new" initialization would never work?

Upvotes: 0

Views: 573

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074208

The only private constructor in your question is SubAlpha, which SubAlpha itself is calling. There's no issue, a class can call its own private methods. The Alpha constructor is protected, so SubAlpha has access to it.

Edit: Re your edit: Yes, exactly. A separate class (whether a subclass or not) would not have access to SubAlpha's private constructor and could not successfully construct a new SubAlpha().

Example 1:

public class Beta
{
    public static final void main(String[] args)
    {
        new SubAlpha();
//      ^--- Fails with a "SubAlpha() has private access in SubAlpha"
//           compilation error
    }
}

Example 2:

public class SubSubAlpha extends SubAlpha
{
    private subsubAlpha()
    {
//  ^== Fails with a "SubAlpha() has private access in SubAlpha"
//      compilation error because of the implicit call to super()
    }
}

This is, of course, constructor-specific, since scope is always member-specific. If a class has a different constructor with a different signature and a less restrictive scope, then a class using it (including a subclass) can use that other constructor signature. (In the case of a subclass, that would require an explicit call to super(args);.)

Upvotes: 5

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

The code works as the main method is also in the same class. You may not be able to initialize SubAplha from a different class.

Upvotes: 1

Related Questions