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

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值