How to override a class within an Android library project?

前端 未结 3 928
谎友^
谎友^ 2020-12-30 05:36

The following is my situation:

I have a library project and a project based on it. Now in the library I have two classes A and B, whereby A uses B. In the project

3条回答
  •  太阳男子
    2020-12-30 06:36

    As I see from your comment you have class A that uses class B

    But class B should be different according to which project you're using.

    I think you need to create a base class say BaseB that will be an instance variable in class A, and you might have a setter and getter for this Or you can make it a parameter passed to the constructor of class A. and when instantiating A you should choose which one to use.

    Let's have a look at code

    Class A {
     private BaseB b;
     public A(BaseB aB) {
       b = aB;
     }
    
     public void set(BaseB aB) {
      b = aB;
     }
     public BaseB get() {
       return b;
     }
    }
    
    interface BaseB {
    }
    
    
    // in the library have this
    class B implements BaseB {
    }
    
    // in your project have the other implementation
    class B implements BaseB {
    }
    
    // you can then instantiate A like this
    A a = new A(new B());
    // you can choose which one to use here in the previous statement.
    

提交回复
热议问题