问题描述
package hf;
import javax.sound.midi.*;
public class BeatBox1
{
public static void main(String[] args)
{
BeatBox1 boom = new BeatBox1();
boom.go();
}
public void go()
{
try
{
Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ,4);
Track track = seq.createTrack();
for(int i = 5;i<125;i+=5)
{
track.add(makeEvent(144,i,i));
track.add(makeEvent(128,i,i+2));
}
player.setSequence(seq);
player.start();
}
catch(Exception e)
{
System.out.println("Problem starting the BeatBox");
}
}
public static MidiEvent makeEvent(int onOff,int note,int time)
{
MidiEvent event = null;
try
{
ShortMessage a = new ShortMessage();
a.setMessage(onOff,1,note,100);
event = new MidiEvent(a,time);
return event;
}
catch(Exception e)
{
System.out.println("Error in creating Event.");
}
return event;
}
}
我在一本书中找到了上面的示例代码.他们建议使makeEvent方法为静态.是什么原因?
I found the above example code in a book. They recommend making the makeEvent method static. What is the reason?
当使makeEvent()也为非静态时,程序也可以正确运行.通过使该方法静态化,可以获得任何性能提升或优势吗?
The program runs correctly when makeEvent() is made non-static as well. Is there any performance gain or any advantage that can be obtained by making the method static?
推荐答案
基于一般的OOP原则,方法实际上是您的类向其实例的公共视图提供的行为".实例是该类抽象存在"的真实版本.现在,在这里要了解的重要一点是,实例方法是类演示的行为.该类的行为与其状态"相关.变量或属性.对于状态的不同值,类的相同方法可以显示不同的行为,即执行的操作.
Based on general OOP principles, a method is actually a 'behavior' which your class offers to public views of its instance. An instance is a real life version of the 'abstract existence' of the class. Now the important thing to understand here is that instance methods are behaviors that the class demonstrates. The behaviors of the class are tied to its 'state' ie. the variables or properties. For different values of state the same method of the class can show different behaviors i.e: operations performed.
因此,作为一般规则:当一种方法提供的行为取决于实例的状态,并且该行为对于该类而言是唯一的时,它应该是非静态的,并且应封装在该类中.仅应通过明确定义的合同将这种行为暴露给世界,该合同通常是公共方法或类的接口.
Thus as a general rule: when a method offers a behavior that is dependent on the state of the instance and the behavior is unique to the class it should be non static and encapsulated in the class. Such a behavior should be exposed to the world only through a well defined contract, that normally is a public method or an interface of the class.
但是,当方法提供的通用行为既不受任何类或实例状态的束缚,也不受状态变化的影响时,它应该是静态的,即:独立于任何类.例如,将给定日期转换为字符串,或登录消息,或转换异常等.
However when a method offers generic behavior not tied to any class or instance state nor influenced by the change in state it should be static i.e: independent of any class. Some examples are converting a given date to string, or loggin a message, or converting exceptions etc.
看看适合您的情况.
这篇关于使方法makeEvent()静态有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!