Java interface

来源:互联网 发布:知乎 中东地区植物 编辑:程序博客网 时间:2024/05/22 14:35

Java interface的使用

在使用接口定义需要注意几点:
1. 每个interface的所有方法的权限为public。
2. 实现接口的非抽象类必须要实现该接口的所有方法。抽象类可以不用实现。

Which should you use, abstract classes or interfaces?

Consider using abstract classes if any of these statements apply to your situation:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.

package com.hotmail.henrytien;interface Inter1{    public static String color = "Red";    public void show();}interface Inter2{    public void play();            }class A implements Inter1,Inter2{    @Override    public void show() {        System.out.println("show");    }    @Override    public void play() {        System.out.println("play");    }}public class InterFaceLearn {    public static void main(String[] args) {        // TODO Auto-generated method stub        A i = new A();        i.show();        i.play();        System.out.println(Inter1.color);    }}

output:
show
play
Red


0 0
原创粉丝点击