Android中BaseActivity应定义为抽象类还是普通类?有何特定原因?
Great question! It’s totally understandable that both approaches work (since you’re not registering BaseActivity in the Manifest), but using an abstract class for your base Activity offers several key benefits that make it the standard choice in Android development. Let’s break down the specific reasons:
Prevent accidental direct instantiation
A core purpose ofBaseActivityis to serve as a template for other Activities to inherit from—it’s never meant to be launched or instantiated on its own. Marking it abstract ensures this at compile time: if someone tries to writenew BaseActivity()or accidentally register it in the Manifest, the compiler will throw an error immediately. With a regular class, this mistake would only surface at runtime (like a crash from missing content view), which is harder to catch early.Clearer design intent for other developers
Abstract classes act as built-in documentation. Any developer looking at your code will instantly know: "This class is a base template—don’t use it directly, extend it instead." A regular class leaves room for ambiguity: someone might wonder if they can instantiate it directly, or if it’s meant to be a parent class. This clarity reduces confusion and keeps your codebase maintainable.Force subclasses to implement required logic
As your app grows, you’ll likely need to add methods that every subclass Activity must implement—things likesetupViews(),initializeViewModel(), orhandlePermissions(). With an abstractBaseActivity, you can define these as abstract methods, which compels subclasses to provide their own implementation. For example:public abstract class BaseActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); setupViews(); } // Subclasses MUST provide a layout ID protected abstract int getLayoutId(); protected abstract void setupViews(); }A regular class can’t enforce this—you’d have to leave empty method bodies, and subclasses might forget to override them, leading to silent failures or missing functionality.
Avoid incomplete implementation issues
BaseActivitytypically contains shared logic (like handling back presses, toolbar setup, or analytics tracking) but doesn’t have its own complete UI or business logic. If it were a regular class, launching it accidentally (even if not registered) could cause crashes (e.g., nosetContentViewcalled). Abstract classes eliminate this risk entirely because they can’t be instantiated.
Even if your current BaseActivity only has constants and helper methods with no abstract requirements, using an abstract class is still a good practice. It future-proofs your code—when you need to add mandatory methods later, you won’t have to refactor the class type, and you’ll maintain consistent design patterns across your app.
内容的提问来源于stack exchange,提问作者Deepak

