为什么我们不能将所有方法和变量设为静态,以免除创建对象的麻烦?
这个问题其实我从很早开始学习Java就一直有,但是从来没有问过。我知道如果方法或变量不是静态的,您可以使用您创建的对象来调用它:
public class classwithmethodandvariable {
int i = 7;
public void hello() {
}
}
你可以这样调用它:
public class myMainClass {
classwithmethodandvariable obj = new classwithmethodandvariable();
classwithmethodandvariable.i++; // ACCESS INT I AND INCREMENT
classwithmethodandvariable.hello(); // CALLS METHOD HELLO
}
但是,如果我们创建了方法 hello()
和变量i
我们可以用更少的代码行完成所有事情,对吗?
public class classwithmethodandvariable {
static int i = 7;
public static void hello() {
}
}
你可以这样调用它:
public class myMainClass {
classwithmethodandvariable.i++; // ACCESS INT I AND INCREMENT
classwithmethodandvariable.hello(); // CALLS METHOD HELLO
}
我们为什么不这样做呢?我见过another question像这样,但答案是“因为你无法从静态方法访问实例变量”。但是如果你也将变量设置为 static
会怎么样? ?
最佳答案
面向对象编程旨在隐藏对象中的状态,然后提供修改状态的方法(也称为行为)。
这是一个非常简单的想法,但是当与继承、接口(interface)和其他常见设计模式结合使用时,可以实现一个非常可维护的系统。
仅使用静态方法会阻止许多设计模式发挥作用,因此您将牺牲系统的可维护性和可扩展性。
关于java - 为什么我们不把所有东西都静态化呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34572117/