Java-hb-36 Interface

1. Definitions

  • Interface definitions : is a collection of abstract methods and constant values. Essentially, the interface is a special kind of abstract class.
  • Interface format :
[public] interface interfacename [extends SuperInterfaceList]{//可继承多个接口
    [public static final] int i = 20;
    [public abstract] void f();
    ...... //常量定义和方法定义
}
  • Interface defined in [attributes] must be public static final
    methods must be public abstract, may be omitted
  • Interface Interface inheritable


2, to achieve

Class can implement an interface, the method may override, override must be added public

interface It{
    int i = 20;
    void f();
}
abstract class A implements It{ //把接口中的成员包含到类A中
    public void f(){//重写必须加public
        System.out.printf("i = %d\n",i);
    }  
}

Inheritance put in front of, behind put implement the interface, for example:

class T extends A implements It4,It3{

}


3, the initial value problem

class A{
    int i;

    public void show(){
        System.out.printf("show-> %d\n",i);  //i是属性i,此时的i等价于this.i
    }

    public void f(){
        int i;  //这里的i和属性i没有冲突
        System.out.printf("f-> %d\n",i);  //error 因为i是局部变量,使用时必须初始化
    }

    public void g(int i){ //i是形参i,形参i也是局部变量
        this .i = i;
        System.out.printf("g-> %d\n",i);
    }
}


4, polymorphism

interface It{
    void f();
}
class A implements It{
    public void f(){
        System.out.printf("AAAA\n");
    }
}

class D{
    public static void main(String[] args) {
        It it;
        it = new A();
        it.f();//输出:AAAA
        it.g();//error
    }
} 
  • The interface (abstract), you can define an object that implements the interface ( new A()), send the address of the object to the reference to the interface, you can call this the real object interface points (by reference to the interface of Athose members) in.
  • By reference interface you can only call a subclass ( A) from the parent class ( Itinherited) over members ( f()), can not be called a subclass-specific ( g()).


5, functions as an interface

  • Interface can achieve the same kind of behavior is not related by
      Java requires all can do self-replicating function of the class must implement: as java.lang.Colneablean interface, but this interface is empty, nothing, just to play the role of a flag.
  • Interface provides a platform for collaboration of different objects
      , such as event handling
  • Interface can achieve multiple inheritance, a class can only make up a single defect inherited from a certain extent.
  • Interface enables us to understand the function of an important way to a class.
      Such as: Java entire container frame is built up by way of the interface, the interface implementation class different is done different functions, the interface is a class that we understand the function of important ways.

Guess you like

Origin www.cnblogs.com/aabyss/p/12317460.html