笔者刚开始了java学习,由于也不是相关专业的,刚学起来有点吃力。
学的时候一直在想,为什么一直要public static void main(){ }
在看《head first java》的时候更加疑惑,只会照着书上敲代码,但是很多疑惑。特别是一会用静态方法,一会又不用。比如这一段代码:
import javax.sound.midi.*;
public class MiniMusicPlayer1 {
public static void main(String[] args) {
try {
Sequencer sequencer=MidiSystem.getSequencer();
sequencer.open();
Sequence seq=new Sequence(Sequence.PPQ,4);
Track t=seq.createTrack();
for(int i=5; i<61; i+=4) {
System.out.println(i);
t.add(makeEvent(144,1,i,100,i));
t.add(makeEvent(128,1,i,100,i+2));
}
sequencer.setSequence(seq);
sequencer.setTempoInBPM(220);
sequencer.start();
} catch(Exception ex) {
ex.printStackTrace();
}
}
public static MidiEvent makeEvent(int comd,int chan,int one,int two,int tick) {
MidiEvent event=null;
try {
ShortMessage a=new ShortMessage();
a.setMessage(comd,chan,one,two);
event=new MidiEvent(a,tick);
} catch(Exception x) {}
return event;
}
}
以为查阅网上资料这么说的:静态方法,只能调用静态的方法,或实例的方法
终于有点懂了,所以如果上面代码不用静态方法的话,那么必须
public static void main(){
new A().functionA(); //这样不会报错
}
下面是更改后的代码,可以运行
import javax.sound.midi.*;
public class MiniMusicPlayer1 {
public static void main(String[] args) {
try {
Sequencer sequencer=MidiSystem.getSequencer();
sequencer.open();
Sequence seq=new Sequence(Sequence.PPQ,4);
Track t=seq.createTrack();
for(int i=5; i<61; i+=4) {
System.out.println(i);
t.add(new MiniMusicPlayer1().makeEvent(144,1,i,100,i));
t.add(new MiniMusicPlayer1().makeEvent(128,1,i,100,i+2));
}
sequencer.setSequence(seq);
sequencer.setTempoInBPM(220);
sequencer.start();
} catch(Exception ex) {
ex.printStackTrace();
}
}
public MidiEvent makeEvent(int comd,int chan,int one,int two,int tick) {
MidiEvent event=null;
try {
ShortMessage a=new ShortMessage();
a.setMessage(comd,chan,one,two);
event=new MidiEvent(a,tick);
} catch(Exception x) {}
return event;
}
}