问题描述
为什么我们不能让所有的方法和变量都是静态的,从而避免创建对象的麻烦?
自从我很久以前开始学习 Java 以来,我实际上一直有这个问题,但从未问过它.我知道如果一个方法或变量不是静态的,你可以使用你创建的对象调用它:
I have actually had this question ever since I started learning Java a long time ago, but never asked it. I know that if a method or variable is not static, you can call it using an object you create:
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
,我们就可以用更少的代码行完成所有事情,对吗?
But, if we had made the method hello()
and variable i
we could have done everything with less lines of code, right?
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
}
我们为什么不这样做?我见过这样的另一个问题,但答案是因为你不能从静态方法访问实例变量".但是如果你让变量也static
怎么办?
Why don't we do that? I have seen another question like this, but the answer says "Because you can't access instance variables from static methods". But then what if you make the variables also static
?
推荐答案
面向对象编程旨在隐藏对象中的状态,然后提供修改状态的方法(也称为行为).
Object oriented programming is designed to hide state in an object and then provide a method (aka behavior) that modifies the state.
这是一个非常简单的想法,但是当与继承、接口和其他常见设计模式结合使用时,可以构建一个非常易于维护的系统.
This is a very simple idea, but when combined with inheritance, interfaces, and other common design patterns allows for a very maintainable system.
仅使用静态方法会阻止这些设计模式中的许多工作,因此您将牺牲系统的可维护性和可扩展性.
The use of only static methods would prevent many of these design patterns from working, and so you would sacrifice maintainability, and extensibility of your system.
这篇关于为什么我们不让一切都静止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!