Java中的内部类和静态嵌套类之间的主要区别是什么?设计/实施是否在选择其中一个方面发挥作用?
我有两个班级A和ClassB:
static class ClassA
{
static string SomeMethod()
{
return "I am a Static Method";
}
}
class ClassB
{
static string SomeMethod()
{
return "I am a Static Method";
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道ClassA.SomeMethod();和之间有什么区别ClassB.SomeMethod();
如果可以在不创建类实例的情况下访问它们,为什么我们需要创建静态类而不是仅使用非静态类并将方法声明为静态?
假设您在非静态类中有一些可以变为静态的方法.
例如:
private double power(double a, double b)
{
return (Math.Pow(a, b));
}
Run Code Online (Sandbox Code Playgroud)
您是否看到将方法签名更改为静态有什么好处?在上面的例子中:
private static double power(double a, double b)
{
return (Math.Pow(a, b));
}
Run Code Online (Sandbox Code Playgroud)
即使有一些性能或内存增益,编译器也不会在编译时进行简单的优化吗?
class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d.show();
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我不了解在其前面带有static关键字的Demo类的创建对象d的用法。如果我消除了static关键字,则会显示错误。实际上,我正在经历匿名的内部类概念,并被困在这里。需要帮助...。任何人都可以解释一下吗?
剧透:这篇文章可能由于使用C和Java编程新手而有些愚蠢
有一个活动MainActivity和一个包含许多方法的公共非活动类。我需要为其中一些显示烤面包警报
当前的尝试是这样的,但对于getApplicationContext()失败,并显示“无法从静态上下文引用非静态方法”:
void errorWarn (String warning) {
Context context = android.content.ContextWrapper.getApplicationContext();
Toast.makeText(context, "Something's wrong in " + warning, Toast.LENGTH_SHORT).show();
}
Run Code Online (Sandbox Code Playgroud)
那么,如何从非活动类中调用吐司呢?
UPD:将从类中的方法中调用errorWarn 。因此,如果在类的方法中发生错误,则应该发出警报
我们在MainActivity中有一个editText字段。该类应从中获取并解析字符串。如果在某些步骤上处理失败,则在MainActivity中显示吐司
UPD2:完整结构。
主要活动:
public class MainActivity extends ActionBarActivity {
<...>
public void ButtonClick (View view) {
Class.testfunc("");
}
}
Run Code Online (Sandbox Code Playgroud)
类:
public class Class {
void errorWarn (Context context, String warning) {
Toast.makeText(context, "Something must be wrong. " + warning, Toast.LENGTH_SHORT).show();
}
void testfunc (String string) {
errorWarn(string);
}
}
Run Code Online (Sandbox Code Playgroud) 我是 Java 新手。我正在阅读玩具代码,并注意到所有其他方法期望“启动”和“停止”方法都是静态的。由于这个“stop”只能通过“.this.stop()”(“here”行)调用。这样的实现有什么好处,为什么不让“start”和“stop”也成为静态方法呢?
public class MyService {
private MyService() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
MyService.this.stop(); <----- here
} catch (IOException | InterruptedException e) {
...
}
}
});
}
protected void stop() {
....
}
protected void start() {
....
}
public static xxx getXXX() {
return xxx;
}
....
}
Run Code Online (Sandbox Code Playgroud)