1. 程式人生 > >Java中extends與implements使用方法

Java中extends與implements使用方法

        一.extends關鍵字

        extends是實現(單)繼承(一個類)的關鍵字,通過使用extends 來顯式地指明當前類繼承的父類。只要那個類不是宣告為final或者那個類定義為abstract的就能繼承。其基本宣告格式如下:

       [修飾符] class 子類名 extends 父類名{

                 類體

        }

        二.implements關鍵字

        由於Java的繼承機制只能提供單一繼承(就是隻能繼承一種父類別),所以就以Java的interface(介面)來代替C++的多重繼承,通過使用關鍵字implements來在類中實現介面。

繼承只能繼承一個類,但implements可以實現多個介面,只要中間用逗號分開就行了 ,基本語法格式如下:

       [修飾符] class  <類名> [extends 父類名]  [implements 介面列表]{

                 類體

       }

 介面是不同的:類中是有程式實現的,繼承會覆蓋父類定義的變數或者函式;而介面中無程式實現,只可以預定義方法,實現介面時子類不可以覆蓋父類的方法或者變數,即使子類定義與父類相同的變數或者函式,也會被父類取代掉。

        注意:實現一個介面就是要實現該介面的所有的方法(抽象類除外)。

//這是Java中關於Icon介面的原始碼,可以看到介面只預定義方法,而沒有具體實現
public interface Icon
{
    /**
     * Draw the icon at the specified location.  Icon implementations
     * may use the Component argument to get properties useful for
     * painting, e.g. the foreground or background color.
     */
    void paintIcon(Component c, Graphics g, int x, int y);

    /**
     * Returns the icon's width.
     *
     * @return an int specifying the fixed width of the icon.
     */
    int getIconWidth();

    /**
     * Returns the icon's height.
     *
     * @return an int specifying the fixed height of the icon.
     */
    int getIconHeight();
}
//在Swing中通過Icon介面來建立圖示
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class DrawIcon implements Icon{                 //建立DrawIcon類實現介面Icon,要實現該介面的所有的方法
     private int width;
     private int height;                            //全域性變數,width代表圖示寬,height代表圖示高
     public int getIconHeight() {                   
          return this.height;
     }
     public int getIconWidth() {
	return this.width;
     }
     public void paintIcon(Component arg0,Graphics arg1,int x,int y) {
	  arg1.fillOval(x,y,width,height);
     }
     public DrawIcon(int width,int height) {          //帶引數建構函式
          this.width=width;
          this.height=height;
     }
     public static void main(String[] args) {         //主函式
     DrawIcon icon=new DrawIcon(15, 15);              //建立DrawIcon類的例項Icon
     JLabel jl=new JLabel("測試",icon,SwingConstants.CENTER);
     JFrame jf=new JFrame();
     Container c=jf.getContentPane();
     c.add(jl);
     jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
     jf.setSize(200,100); 
     jf.setVisible(true);
     }
}