一.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);
}
}