接口與多態(tài)
接口
- 一種特殊的類,是一種抽象類的延伸。
- 接口之間允許繼承而且允許多重繼承---一個接口可以繼承多個接口。
- 接口只寫方法就可以了。
- 接口中定義的方法必須被定義為public或abstract形式,其他修飾權(quán)限不被Java編譯器認可。
- 接口是可以多實現(xiàn)的:因為接口中的方法都是抽象的,都沒有實現(xiàn),在創(chuàng)建子類對象并調(diào)用該重寫的抽象方法時,很明顯就是調(diào)用重寫之后的方法,不會出現(xiàn)調(diào)用的不確定性。
- 注意:類與類之間是繼承關(guān)系 ,通過繼承可以得到繼承體系的基本功能。接口與接口之間是實現(xiàn)關(guān)系,通過實現(xiàn)接口可以得到繼承體系之外的功能。
實例
- 一個簡單的音樂家的接口,寫和音樂家相關(guān)的方法(彈鋼琴和拉小小提琴)。
public interface Musician {
void playPiano();
void palyViolin();
}
窗口的實現(xiàn)
1、創(chuàng)建一個類去繼承JFrame這個父類。
2、在該類的構(gòu)造函數(shù)中對窗口的一些基本屬性進行初始化操作。
public MyFrame() { // 構(gòu)造函數(shù) 窗口的初始化。
this.setSize(300, 200); // 窗口大小的設(shè)置
this.setResizable(false); // 定義窗口大小是否被改變。
this.setLocationRelativeTo(null); // 窗口的放置位置。
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 關(guān)閉即退出。
this.setLayout(null); // 不要布局管理器
}3、在窗口上添加文本組件
JTextField jTextField = new JTextField("你好瓜",90);
jTextField.setFont(new Font("楷體",Font.CENTER_BASELINE ,20));
jTextField.setBounds(50, 50, 200, 80);
this.add(jTextField);4、在窗口上添加標簽組件
JLabel jLabel = new JLabel("傻不傻");
jLabel.setFont(new Font("楷體", Font.BOLD, 18));
jLabel.setBounds(225,100, 200, 600);
JCheckBox jCheckBox = new JCheckBox("1");
jCheckBox.setBounds(225,100, 200, 50);
this.add(jCheckBox);-
5、在窗口上添加按鈕組件并創(chuàng)建按鈕的事件監(jiān)聽器
JButton jButton = new JButton("按下有驚喜");
jButton.setFont(new Font("楷體", Font.BOLD, 16));
jButton.setForeground(Color.BLUE);
jButton.setBackground(Color.RED);
jButton.setBounds(225, 300, 200, 50);
this.add(jButton);
jButton.addActionListener(e -> {
JOptionPane.showMessageDialog(null, "你好傻??!"); // 消息提示面板}); 6、窗口上Timer的創(chuàng)建與應(yīng)用
Timer timer = new Timer(10, e->{
for (int i = 0; i < total; i++) {
SmallBall smallball = ballarray[i];
smallball.move();
repaint(); //回調(diào)paint()方法,即改變x,y值后再重新渲染一次。} }); timer.start();7、雙緩存讓窗口上的動畫更加的流暢
private BufferedImage image = new BufferedImage(700, 700, 1);
public void paint(Graphics g) {
// TODO Auto-generated method stub
Graphics otherg = image.getGraphics();
super.paint(otherg);
// otherg.setColor(Color.BLUE);
// otherg.fillOval(x<700?x:700-(x-700), y<700?y:700-(y-700), 40, 40);
for (int i = 0; i < total; i++) {
SmallBall smallball = ballarray[i];
smallball.draw(otherg);
}
g.drawImage(image, 0, 0, null);
}-
8、隨機獲得顏色
public Color randomColor() {
int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
return new Color(red, green, blue);
}