-2

When attempting to create an object of the parent class, which has a protected constructor, I tried using a child class reference and was able to create the object successfully. However, when using a parent class reference, it resulted in a compilation error.

When attempting to create an object of the parent class, which has a protected constructor, I tried using a child class reference and was able to create the object successfully. However, when using a parent class reference, it resulted in a compilation error.

This is the code used:

package secondPackage;

public class AccessPra {

    protected AccessPra() {
        System.out.println("protected constructor");
    }
}
package firstPackage; 
import secondPackage.*;
public class MainClass extends AccessPra {

    public static void main(String[] args) {

        AccessPra obj1 = new AccessPra();  // Throwing Error
        
        MainClass obj2 = new MainClass();  // This line is working

    }

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

-2

Because they are in different packages, that has to do with access modifiers, if you move your class into the same package it will work! Check this table to understand access modifiers: https://www.javatpoint.com/access-modifiers

like this:

package firstPackage;
public class AccessPra {

    protected AccessPra() {
        System.out.println("protected constructor");
    }
}

package firstPackage; 
public class MainClass extends AccessPra {

    public static void main(String[] args) {

        AccessPra obj1 = new AccessPra();  // No Error

    }

}

If you want different packages and use protected methods using inheritance you can also do this:

package secondPackage;

public class AccessPra {

    public AccessPra() {
        
    }

    protected void protectedMethod() {
        System.out.println("protected method");
    }
}



package firstPackage;
import secondPackage.*;

public class MainClass extends AccessPra {

    public static void main(String[] args) {

        MainClass obj1 = new MainClass();  // This line is working
        obj1.protectedMethod();
    }

}

As you can see, as the mainclass extends AccesPra, it inherits the methods from the parent Class and because of that you can use them when they are protected.

Hope that helps!

Mikebar
  • 1
  • 1
  • `protected` allows any intra-package access, yes, but the question is why the inheritance isn’t enough. – Davis Herring Jun 03 '23 at 01:17
  • The problem is not about "enough", you create a class MainClass that is an instance of AccessPra, and because of that it is already an object of that type, that is just bad programming not an access modifier issue, i am sorry! but stackOverflow is here to help! – Mikebar Jun 03 '23 at 01:25
  • I edited my answer to show you an example – Mikebar Jun 03 '23 at 01:26