Nikhil
Nikhil

Reputation: 101

Accessing Inherited subclass in a different package

package 1; // this is a dependency library

public class A{

public String getName(){
return "In func getName, class A";
}

}

-------------------------------------------
package 2; // this is the library which I am building
import 1;

public class B extends A{

}

----------------------------------------------
package 3; // this is the app which is using the library which I am building
import 2;

public class C {

B b = new B(); // throws error here, says "Cannot access A"
b.getName();
}

this throws an error B b = new B(); I am not sure what is the issue here, this should work fine right?

I am working on building a library where I am extending a class from dependency library class. Now I am using the library which I built in an app and when I try to access the inherited class it throws an error.

I added dependency library as following in the library I am building

implementation ':dependencyLibrary'

In the app using my library

include ':mylibraryName' implementation project(':mylibraryName')

I just don't want the 'dependencyLibrary' accessible to the app

Upvotes: 0

Views: 514

Answers (1)

Bonfix Ngetich
Bonfix Ngetich

Reputation: 1237

You are seeing this error because you have not linked your library to your current project. You need to link the library project to your current project so that the import statement works.

One way of doing this is by:

  1. Go to File -> New -> Import Module ->
  2. Add library to include section in settings.gradle file and sync the project (After that you can see new folder with library name is added in project structure)

include ':mylibraryName'

  1. Go to File -> Project Structure -> app -> dependency tab -> click on plus button

  2. List item

Select module dependency -> select library (your library name should appear there) and put scope (compile or implementation)

  1. Add this line in build.gradle in app level module in dependency section
implementation project(':mylibraryName')

Upvotes: 1

Related Questions