Search code examples
javainheritanceconstructordefaultaccess-modifiers

Why does a Java constructor have to be public or protected for a class to be extended outside its package?


The following is my ProtectedConstructor.java source code:

package protectCon;

public class ProtectedConstructor{
    public int nothing;
    ProtectedConstructor(){
        nothing = 0;
    }
}

And following is the UsingProtectedCon.java source:

package other;

import protectcon.ProtectedConstructor;

public class UsingProtectedCon extends ProtectedConstructor{   //**Line 4**
    public static void main(String... a) {  
    }
}

When I compile UsingProtectedCon.java, I get error at Line 4 shown above. It says that ProtectedConstructor() is not public ; so cannot be accessed outside package.

However, since my class is public, shouldn't I be able to extend it outside package. I am anyway not creating any instance of it.

Now, if I make the constructor of ProtectedConstructor class as public or protected then the code compiles fine with no error.

So then why is it necessary even for the constructor to be public or protected, and not just have default access?


Solution

  • If you want to extends a class outside its package it must have a constructor that is public or protected because in Java every constructor must call a constructor from its superclass.

    Because of this there is an implied super() call in every constructor which does not have this() or an explicit call to super() as its first statement. And if you don't specify a constructor at all Java will add a default parameterless constructor, so in effect your code looks like this:

    public class UsingProtectedCon extends ProtectedConstructor {
        public UsingProtectedCon() {
            super();
        }
    
        public static void main(String... a) {   
        }
    }
    

    So in other words your code is failing to compile because the call to super() in the default constructor cannot be resolved.