在java中如何解决在使用接口时而不实现所有的方法? 求实列。
java
------解决方案--------------------
interface A{
public void fun1() ;
public void fun2() ;
}
//因为B类是抽象类,所以不能直接实例化
abstract class B implements A{
public void fun1(){
}
public void fun2(){
}
}
//C类只覆写B类的fun2()方法
class C extends B{
public void fun2(){
... //方法体
}
}
------解决方案--------------------
楼主的这种需求使用适配器Adapter
楼主可以先查查,至于实例么,Swing 里面事件监听里使用
Adapter的地方多得很
例如对于一个JButton注册监听MouseListener
我们必须实现该接口的所有方法
但是我们可以注册MouseListener的实现类MouseAdapter
就可以有选择的实现我们需要的方法。
其实这个Adapter什么也没做,只是实现接口,方法也并没有实现
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.awt.event;
/**
* An abstract adapter class for receiving mouse events.
* The methods in this class are empty. This class exists as
* convenience for creating listener objects.
* <P>
* Mouse events let you track when a mouse is pressed, released, clicked,
* moved, dragged, when it enters a component, when it exits and
* when a mouse wheel is moved.
* <P>
* Extend this class to create a {@code MouseEvent}
* (including drag and motion events) or/and {@code MouseWheelEvent}
* listener and override the methods for the events of interest. (If you implement the
* {@code MouseListener},
* {@code MouseMotionListener}
* interface, you have to define all of
* the methods in it. This abstract class defines null methods for them
* all, so you can only have to define methods for events you care about.)
* <P>
* Create a listener object using the extended class and then register it with