Java學(xué)習(xí)第14天

接口

  • (英文:Interface),在JAVA編程語言中是一個抽象類型,是抽象方法的集合,接口通常以interface來聲明。一個類通過實現(xiàn)接口的方式,從而來繼承接口的抽象方法。

  • 接口是方法聲明的集合。接口里的方法是自動公開的而且都是抽象的,編譯器會自動加上public abstract

  • 接口里的方法都是抽象的,不能再接口中實現(xiàn)。但是Java 8 以后,接口中的方法可以通過default來默認實現(xiàn)。實現(xiàn)接口的類在實現(xiàn)接口(implements)的方法中可以重寫這些方法,若不重寫,這些方法會使用默認的實現(xiàn)方法(default)

  • 一個類只能繼承一個抽象類,而一個類卻可以實現(xiàn)多個接口,通過逗號連接

  • 接口沒有構(gòu)造方法

  • 接口可以多重繼承(可以繼承其他接口)

  • 類和類之間簡單的說有三種關(guān)系:

  1. is-a 關(guān)系 - 繼承 - 學(xué)生和人
  2. has-a關(guān)系 - 關(guān)聯(lián)(聚合/合成) - 撲克和一張牌
  3. use-a關(guān)系 - 依賴 - 人和房子
  • 類和它實現(xiàn)的接口之間的關(guān)系:
    play-a / like-a - 實現(xiàn)

#######接口案例:

  • 爸爸類
package org.mobiletrain;

public class Father {

    protected String name;
    
    public Father(String name) {
        this.name = name;
    }
    
    public void gamble(){
        System.out.println(name + "正在賭博");
    }
}
  • 和尚類
package org.mobiletrain;


public interface Monk {

    public default void chant(){
        System.out.println("hello");
    }
    
    public void eatVegetable();
    
    public void knockTheBell();
}
  • 音樂家類
package org.mobiletrain;

public interface Musician {

    void playPiano();
    
    void playViolin();
}
  • son類繼承了father類,同時實現(xiàn)了monk和musician接口
package org.mobiletrain;

public class Son extends Father implements Monk,Musician {

    public Son(String name) {
        super(name);
        
    }

    public void somke(){
        System.out.println(name + "正在抽煙");
    }

    @Override
    public void chant() {       
         System.out.println(name + "正在念《大悲咒》");
    }

    @Override
    public void eatVegetable() {
        System.out.println(name + "正在念吃齋");
    }

    @Override
    public void knockTheBell() {
        System.out.println(name + "正在敲鐘");
    }

    @Override
    public void playPiano() {       
        System.out.println(name + "正在彈鋼琴");
    }

    @Override
    public void playViolin() {
        System.out.println(name + "正在拉小提琴");
    }
    
    
}

Java 8 出現(xiàn)的適配器(Adapter)

  • 使用適配器,可以選擇性地實現(xiàn)一個接口中的某些方法;

####### 鼠標點擊,出現(xiàn)隨機顏色隨機大小的圓,且不會移動出邊框

  • 先創(chuàng)建一個ball類
package org.mobiletrain.ui;

import java.awt.Color;
import java.awt.Graphics;

/**
 * 小球
 * @author apple
 *
 */
public class Ball {

    protected Color color;//顏色
    protected int x;    //左上角橫坐標
    protected int y;    //左上角縱坐標
    protected int size; //尺寸
    protected int sx;   //速度在橫坐標上的分量
    protected int sy;   //速度在縱坐標上的分量
    
    public Ball(Color color,int x,int y,int size,int sx,int sy) {
        this.color = color;
        this.x = x;
        this.y = y;
        this.size = size;
        this.sx = sx;
        this.sy = sy;
    }

    public void move(){
        x += sx;
        y += sy;
        
        if (x <= 0 || x > 800 - size) {
            sx = -sx;
        }
        
        if (y <= 30 || y >= 600 - size) {
            sy = -sy;
        }
    }
    
    public void draw(Graphics g){
        g.setColor(color);
        g.fillOval(x - size / 2, y - size / 2, size, size);
    }
    
}
  • 再創(chuàng)建一個窗口(繼承JFrame)
package org.mobiletrain.ui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.Timer;

//動畫
@SuppressWarnings("serial")
public class Frame extends JFrame {
    private BufferedImage image = new BufferedImage(800, 600, 1);
    //private Ball ball = new Ball(Color.BLUE, 20, 30, 80, 4, 4);
    private Ball ballsArray[] = new Ball[100];
    private int total = 0;
    
    public Frame(){
        this.setSize(800,600);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e){
                if (total < ballsArray.length) {
                    int x = e.getX();
                    int y = e.getY();
                    int size = (int) (Math.random() * 81 + 20);
                    int sx = (int) (Math.random() * 20 - 10);
                    int sy = (int) (Math.random() * 20 - 10);
                    Color color = getRandmColor();
                        Ball ball = new Ball(color, x, y, size, sx, sy);
                        ballsArray[total++] = ball;             
                }
            }
        });
        
        
        Timer timer = new Timer(40, e -> {
            //ball.move();
            for (int i = 0; i < total; i++) {
                ballsArray[i].move();
            }
            repaint();
        });
        timer.start();
    }
    
    public Color getRandmColor(){
        int r = (int) (Math.random() * 256);
        int g = (int) (Math.random() * 256);
        int b = (int) (Math.random() * 256);
        return new Color(r, g, b);
    }
    
    @Override
    public void paint(Graphics g) {
        Graphics otherGraphics = image.getGraphics();
        super.paint(otherGraphics);
        //ball.draw(otherGraphics);
        for(int i = 0;i < total;i++){
            ballsArray[i].draw(otherGraphics);
        }
        g.drawImage(image,0,0,null);
    }
    
    
    public static void main(String[] args) {
        new Frame().setVisible(true);
    }
}

lambda表達式

  • Java 8+ ---> lambda表達式(匿名函數(shù))
    僅限于接口中只有一個方法,而且沒有默認實現(xiàn)

#######在窗口設(shè)置一個按鈕,點擊按鈕,窗口背景顏色更改

package org.mobiletrain.ui;

import java.awt.Color;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;


import javax.swing.JButton;
import javax.swing.JFrame;

@SuppressWarnings("serial")
public class MyFrame extends JFrame {

    public MyFrame(){
        this.setSize(300,200);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(null);
        
        JButton okButton = new JButton("確定");
        okButton.setBounds(120, 100, 60, 30);
//      ActionListener listener = new ActionListener() {
//          
//          //只有一個方法的接口(函數(shù)接口),里面的方法通常都是回調(diào)方法
//          //接口的回調(diào)(callback)方法
//          @Override
//          public void actionPerformed(ActionEvent e) {
//              changeBgColor();
//              
//          }
//      }
        
        //Java 8+ ---> lambda表達式(匿名函數(shù))
        //僅限于接口中只有一個方法,而且沒有默認實現(xiàn)
        okButton.addActionListener(e -> {
            changeBgColor();
        });
        //okButton.addActionListener(listener);//動作監(jiān)聽器,監(jiān)聽按鈕的點擊事件
        this.add(okButton);
    }
    
    public void changeBgColor(){
        int r = (int) (Math.random() * 256);
        int g = (int) (Math.random() * 256);
        int b = (int) (Math.random() * 256);
        this.getContentPane().setBackground(new Color(r, g, b));
    }
    
    public static void main(String[] args) {
        new MyFrame().setVisible(true);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,706評論 18 399
  • 轉(zhuǎn)自:http://blog.csdn.net/jackfrued/article/details/4492194...
    王帥199207閱讀 8,806評論 3 93
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,058評論 25 709
  • 沒有 到更南的地方看一看 認定北方的天更清 漫雪 是天地的盛裝舞會 墨發(fā)低垂的女孩揚眉起舞 足尖右點 左邊足印又淹...
    W_li閱讀 269評論 2 3
  • 認識我的人絕不相信,我也曾安靜過。 我原本是一個極其安靜的小姑娘。一早背著書包來,放學(xué)背著書包走;下午...
    西哈哈閱讀 277評論 0 1

友情鏈接更多精彩內(nèi)容