Java中的接口与抽象类

来源:互联网 发布:ipad一键越狱软件 编辑:程序博客网 时间:2024/05/30 04:35

声明:本文为原创,欢迎转载,转载请注明出处。


接口的子类要么必须实现父类的方法,要么把自己定义成抽象类。抽象类可以定义抽象方法。

抽象类的子类要么必须实现父类的抽象方法,要么也把自己定义成抽象类。

如果类A的父类B继承自一个接口或者抽象类C,而B如果是个抽象类并且没有实现C的方法,那么A要么必须实现C的方法,要么把自己定义为抽象类。

综上所述,接口和抽象类都不能被实例化,只能通过其子类来实现。接口和抽象类不管被继承了多少个层次,对于其第一个不是抽象类的子类来说,必须实现它们的方法。


为了验证以上的结论,设计了一个小程序:


首先写一个接口,接口只能声明方法而不能实现它,接口可以有数据成员,但一般只包含方法:

public interface SunInterface {public void myPrint();} 

然后设计一个子类Child1来继承接口,在实现接口之前,eclipse会有如下提示:

可见接口的子类要么实现接口,要么作为抽象子类。



因此,设计Child1来实现接口,SunAbstract作为抽象子类并没有去实现myPrint,他们都定义了自己的成员变量和方法,SunAbstract还可以定义抽象方法,SunAbstract本身不能实现抽象方法,必须留给子类去实现。

public class Child1 implements SunInterface {private String myStr1 = "";protected void setStr(String str) {myStr1 = str;}protected String getStr(String str) {return myStr1;}@Overridepublic void myPrint() {System.out.print("myPrint in Child1.\n");}public void myPrint1() {System.out.print("myPrint1 in Child1, myStr1 is" + myStr1 + "\n");}}

public abstract class SunAbstract implements SunInterface {private String myStrAbstract = "";protected void setStr(String str) {myStrAbstract = str;}protected String getStr(String str) {return myStrAbstract;}public void myPrintAbstract() {System.out.print("myPrintAbstract in sunAbstract, myStrAbstract is" + myStrAbstract + "\n");}public abstract void myPrintAbstract_Abstract();}


Child2是SunAbstract的子类,亦即是接口SunInterface的子类,Child2如果不是抽象类,那它必须实现SunInterface的方法。

public class Child2 extends SunAbstract {@Overridepublic void myPrintAbstract_Abstract() {System.out.print("myPrintAbstract_Abstract in Child2\n");}@Overridepublic void myPrint() {System.out.print("myPrint in Child2\n");}}

测试代码如下:

public class SunTest {public static void main(String[] args) {Child1 ch1 = new Child1();ch1.myPrint();ch1.setStr("Sun1");ch1.myPrint1();Child2 ch2 = new Child2();ch2.myPrint();ch2.setStr("Sun2");ch2.myPrintAbstract();ch2.myPrintAbstract_Abstract();}}

运行结果如下:

myPrint in Child1.
myPrint1 in Child1, myStr1 isSun1
myPrint in Child2
myPrintAbstract in sunAbstract, myStrAbstract isSun2
myPrintAbstract_Abstract in Child2

原创粉丝点击