zoukankan      html  css  js  c++  java
  • 10.7 抽象类与接口

    1、接口概述
      a、接口是抽象类的延伸,可以将它看做是纯粹的抽象类,接口中的所有方法都没有方法体。
      b、接口中定义的方法必须被定义为public或abstract形式,其它修饰权不被java编译器认可,即使不将该方法声明为public形式,它也是public。
      c、接口中定义的任何字段都自动是static和final的。
      语法如下:
        public interface drawTest{
        viod draw(); //接口内的方法,省略abstact关键字
        }
        public:接口可以像类一样被权限修饰符修饰,但是public关键字仅限用于接口卡在与其同名的文件中被定义
        interface:定义接口关键字
        drawTest:接口名称
      例如:一个类实现一个接口可以使用implements关键字,代码如下
        public class Parallelogram extends Quadrangle implements drawTest{
        ...//
        }

    例子10.13【将多态技术与接口结合】

     1 interface drawTest { // 定义接口
     2     public void draw(); // 定义方法
     3 }
     4 
     5 // 定义平行四边形类,该类继承了四边形类,并实现了drawTest接口
     6 class ParallelogramgleUseInterface extends QuadrangleUseInterface
     7         implements drawTest {
     8     public void draw() { // 由于该类实现了接口,所以需要覆盖draw()方法
     9         System.out.println("平行四边形.draw()");
    10     }
    11     
    12     void doAnyThing() { // 覆盖父类方法
    13         // SomeSentence
    14     }
    15 }
    16 
    17 class SquareUseInterface extends QuadrangleUseInterface implements
    18         drawTest {
    19     public void draw() {
    20         System.out.println("正方形.draw()");
    21     }
    22     
    23     void doAnyThing() {
    24         // SomeSentence
    25     }
    26 }
    27 
    28 class AnyThingUseInterface extends QuadrangleUseInterface {
    29     void doAnyThing() {
    30         
    31     }
    32 }
    33 
    34 public class QuadrangleUseInterface { // 定义四边形类
    35     public void doAnyTthing() {
    36         // SomeSentence
    37     }
    38     
    39     public static void main(String[] args) {
    40         drawTest[] d = { // 接口也可以进行向上转型操作
    41         new SquareUseInterface(), new ParallelogramgleUseInterface() };
    42         for (int i = 0; i < d.length; i++) {
    43             d[i].draw(); // 调用draw()方法
    44         }
    45     }
    46 }
    View Code

    2、接口与继承
      a、我们知道在java中不允许多重继承,但使用接口就可以实现多重继承,因为一个类可以同时实现多个接口,这样可以将所有需要继承的接口放置在implements关键字后并使用逗号隔开,但这可能会在一个类中产生庞大的代码量,因为继承一个接口时需要实现接口中所有的方法。
      多重继承的语法如下:
        class 类名 implements 接口1,接口2,...,接口n
      b、在定义一个接口时也可以使该接口继承另外一个接口。
        interface intf1{
        }
        interface intf2 extends intf1{
        }

  • 相关阅读:
    Treap 树堆 容易实现的平衡树
    (转)Maven实战(二)构建简单Maven项目
    (转)Maven实战(一)安装与配置
    根据请求头跳转判断Android&iOS
    (转)苹果消息推送服务器 php 证书生成
    (转)How to renew your Apple Push Notification Push SSL Certificate
    (转)How to build an Apple Push Notification provider server (tutorial)
    (转)pem, cer, p12 and the pains of iOS Push Notifications encryption
    (转)Apple Push Notification Services in iOS 6 Tutorial: Part 2/2
    (转)Apple Push Notification Services in iOS 6 Tutorial: Part 1/2
  • 原文地址:https://www.cnblogs.com/studycode/p/9534432.html
Copyright © 2011-2022 走看看