Java – Combine fragment and activity classes in a base class

Combine fragment and activity classes in a base class… here is a solution to the problem.

Combine fragment and activity classes in a base class

I have 2 classes:

public class MyFragment extends Fragment implements MyListener
public void myFun1()
public void myFun2()
public void myFun23()

public class MyActivity extends AppCompatActivity implements MyListener
public void myFun1()
public void myFun2()
public void myFun34()

I’m trying to merge my two classes into one base class, so I only need to write myFun1() and myFun2() once, but the problem is with a class extension fragment and a class extension activity. How do I centralize these functions in a base class?

EDIT: These methods are not from the Listener and can be ignored. myFun1() and myFun2() have the same features, while myFun23() and myFun34() have special features that are only required in similar products

Solution

You can only use Java8, which introduces the default method in the interface.
You can define things like this:

public interface MyInterface {

default void myFun1() {
          default method implementation
    }

default void myFun2() {
          default method implementation
    }

}

And then:

   public class MyActivity extends AppCompatActivity implements MyListener, MyInterface {

 Just define
     public void myFun23(){}
   }

public class MyFragment extends Fragment implements MyListener, MyInterface {

 Just define
     public void myFun34(){}
   }

You can do the same with kotlin.

interface MyInterface {
    fun myFun1() {
       implementation
    }
    //...
}

And then:

class MainActivity : AppCompatActivity(), MyInterface {

fun func23() {
       //...
    }
}

....

Related Problems and Solutions