java 创建抽象 Activity 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5774782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating abstract Activity classes
提问by zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
I am working on creating abstract activity classes for my application that I will reuse for each activity.
我正在为我的应用程序创建抽象活动类,我将在每个活动中重复使用这些类。
Super Class: android.app.Activity
My Abstract Class extends android.app.ActivitymyActivity
Example activty in my application extends myActivity.
超类:android.app.Activity
我的抽象类扩展了 android.app.ActivitymyActivity
我的应用程序中的示例活动扩展了 myActivity。
I will have 10-20 of these exampleActivity
.
我将有 10-20 个这样的exampleActivity
。
How can I write my abstract class (#2) to force my example class to override methods in android.app.Activity
like onCreate()
and onStart()
?
我如何编写我的抽象类(#2)来强制我的示例类覆盖android.app.Activity
likeonCreate()
和 中的方法onStart()
?
Is this possible in Java?
这在Java中可能吗?
采纳答案by Phil Lello
Not really.
并不真地。
Howeveryou can create abstract functions myOnCreate and myOnStart and call those in your abstract class implementation of onCreate and onStart.
但是,您可以创建抽象函数 myOnCreate 和 myOnStart,并在 onCreate 和 onStart 的抽象类实现中调用它们。
You might also want to make onCreate/onStart final, although it's difficult to see what the benefit is of forcing myOnCreate instead of onCreate.
您可能还希望将 onCreate/onStart 设为 final,尽管很难看出强制使用 myOnCreate 而不是 onCreate 有什么好处。
回答by Bipin Vayalu
This is possible,
这个有可能,
public abstract class MyActivity extends android.app.Activity
{
public abstract void onCreat(...);
public abstract void onStart(...);
}
public class OtherActivity extends MyActivity
{
public void onCreate(...)
{
//write your code
}
public void onStart(...)
{
//write your code
}
}
回答by J.S. Taylor
Nop. It's more elegant to create an interface with onCreate and onStart methods instead if you need force others to override in their implementation.
没有。如果您需要强制其他人在他们的实现中覆盖,那么使用 onCreate 和 onStart 方法创建一个接口会更优雅。
And pass the interface instance to your abstract activity class throught constructors or setters.
并通过构造函数或设置器将接口实例传递给您的抽象活动类。