关于接口为内部时和为外部时的区别与联系

30 篇文章 0 订阅

首先说明,无论接口是在类内部还是外部,都需要覆盖接口定义的所有方法。

至于原因就去查看java教材关于接口的那一章讲解。

 

一、当接口为内部时,在类的头部即public class YY 后不必写implements XX-interface

如:

public class J_Panel extends JPanel
{
 public J_Panel()
 {
  addMouseListener(new MouseListener()
  {
   public void mouseExited(MouseEvent e)
   {}
   public void mouseClicked(MouseEvent e)
   {}
   public void mouseEntered(MouseEvent e)
   {}
   public void mousePressed(MouseEvent e)
   {}
   public void mouseReleased(MouseEvent e)
   {}
  }
  ); // end of addMouseListener
 
  addMouseMotionListener(new MouseMotionListener()
  {
   public void mouseMoved(MouseEvent e)
   {}
   public void mouseDragged(MouseEvent e)
   {}
  }
  ); // End of addMouseMotionListener
 } // End of the conductor of J_Panel

 protected void paintComponent(Graphics g)
 {
  } // End of the function of paintComponent
}

注:若写上了implement MouseListener,

   则编译时会发生错误:

       class J_Panel不是抽象的,未覆盖java.awt.event.MouseListener中的抽象方法.....

   就是说,内部接口的实现并不能覆盖implements MouseListener的抽象方法。

二、而当接口为外部时,必须在类的头部即public class YY 后写上implements XX-interface

如:

public class ScribblePanel extends JPanel implements MouseListener, MouseMotionListener
{ 
 public ScribblePanel()
 {
  // Register listener for the mouse event
  addMouseListener(this);
  addMouseMotionListener(this);
 }
// interface MouseListener
 public void mouseClicked(MouseEvent e)
 {}
 public void mouseEntered(MouseEvent e)
 {}
 public void mouseExited(MouseEvent e)
 {}
 public void mouseReleased(MouseEvent e)
 {}
 public void mousePressed(MouseEvent e)
 {}
 
// interface MouseMotionListener
 public void mouseDragged(MouseEvent e)
 {}
 public void mouseMoved(MouseEvent e)
 {}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值