javaandroidabstract-classself-type

How to avoid downcasting of abstract class to child class?


I have the following structure in my android app:

    abstract class BaseActivity extends AppCompatActivity{
        protected BaseViewModel mViewModel;
    }
    abstract class BaseViewModel extends ViewModel { ... }
    class MainActivityViewModel extends BaseViewModel { ... }
    class MainActivity extends BaseActivity{ ... }

now when initializing the BaseViewModel in the MainActivity i want to enter the type as a generic so i dont have to cast it everytime into the child implmenentation ((MainActivityViewModel)mViewModel), i've read about generic self-typing, but dont understand how this works in this exact scenario.


Solution

  • If you want protected BaseViewModel mViewModel; to have a generic type, you should rewrite you class as follow:

    public abstract class BaseActivity<T> extends AppCompatActivity{
            protected T mViewModel;
        }
    
     public class MainActivity extends BaseActivity<MainActivityViewModel >{ ... }
    

    I hope I answered you question. If I don't, Should you explain a bit more?