Search code examples
javainheritanceconstructoraccess-modifiersdefault-constructor

Default access modifier of constructor in Inheritance


I did a little web search and came to know that default constructor's access modifier is same as the access level of class, but take a look.

Here is one class

package package2;
public class TestClass1 {
    TestClass1()
    {
        System.out.println("In parent's contructor");
    }
}

and here is another which inherits from the previous one

package package2;

public class TestClass2 extends TestClass1 {

      TestClass2()
     {
         System.out.println("In TestClass2's contructor");
     }

}

But when i try to create the object of TestClass2

import package2.*;

class MainClass {


    public static void main(String[] args) 
    {
        TestClass2 t2 = new TestClass2(); //Says the constructor TestClass2() is not visible.

    }
 }

I don't understand, both classes TestClass1 and TestClass2 have public access so their constructors must also be implicitly public. Which concept am I missing here ? o.O


Solution

  • I did a little web search and came to know that default constructor's access specifier is same as the access level of class

    There is a difference between default constructor and the one which you've declared. The default constructor is the one which you don't declare inside the class.

    The current one in your code is not a default constructor. And, it has default(package-private --- no explicit modifier) acccess as you've omitted any access modifier from it.

    Which concept am I missing here ?

    So, your class from other package is not able to find it, because of the limitation of default access.