抽象类与接口

一、抽象类

  抽象类是指包含了抽象方法的类。其中,抽象方法只声明方法名称,而不指明方法体。抽象类如果拥有未实现的方法,不能被实例化。

abstract class AbstractClass{
  public void test1(){
    System.out.println("this is test1");
  }
  public abstract void test2();
}

public class SubClass extends AbstractClass{

  public void test2() {
    System.out.println("this is test2");
  }
  public static void main(String[] args) {
    SubClass s = new SubClass();
    s.test1();
    s.test2();
  }

}

此段代码首先定义了一个抽象类,该类包含两个方法,一个为一般方法,一个为抽象方法。然后定义了另一个类SubClass,继承了抽象类,并且实现了抽象类中的抽象方法。

二、接口

  接口只定义提供什么功能,而不定义功能的具体实现,可以说是抽象类的极端化。一个子类只能实现一个父类,但可以实现多个接口,只能包含常量和抽象方法。

interface InterfaceExm{
  public void test();
}
class TestClass1 implements InterfaceExm{
  public void test() {
    System.out.println("this is test1");
  }
}
class TestClass2 implements InterfaceExm{
  public void test() {
    System.out.println("this is test2");
  }

}

public class TestInterface {
  public static void main(String[] args) {
    InterfaceExm ie;
    ie = new TestClass1();
    ie.test();
    ie = new TestClass2();
    ie.test();
  }
}

以上代码定义了一个简单的接口,其只包含一个抽象方法,然后分别定义了两个实现类,并且实现了其抽象方法。

原文地址:https://www.cnblogs.com/czl362326/p/5621847.html