在其他包中访问继承的子类

时间:2018-10-24 18:27:42

标签: java android oop inheritance android-library

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();
}

这将引发错误B b = new B(); 我不确定这里是什么问题,应该可以正常使用吗?

我正在构建一个库,在该库中我将从依赖库类扩展一个类。现在,我使用的是我在应用程序中内置的库,当我尝试访问继承的类时,它将引发错误。

我在要构建的库中添加了以下依赖库

implementation ':dependencyLibrary'

在使用我的媒体库的应用中

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

我只是不希望应用程序可以访问“ dependencyLibrary”

1 个答案:

答案 0 :(得分:1)

您看到此错误,因为尚未将库链接到当前项目。 您需要将库项目链接到当前项目,以便导入语句起作用。

一种方法是:

  1. 转到文件->新建->导入模块->
  2. 添加库以将部分包含在settings.gradle文件中,并 同步项目(之后,您可以看到带有库的新文件夹 名称已添加到项目结构中)
  

包括':mylibraryName'

  1. 转到文件->项目结构->应用程序->依赖项选项卡->单击 加号按钮

  2. 列表项

选择模块依赖性->选择库(您的库名称应为     出现在此处)并放置范围(编译或实现)

  1. 添加此 依赖项部分中的应用程序级别模块中build.gradle中的行
implementation project(':mylibraryName')