Java中接口interface和实现implements问题

来源:互联网 发布:mac退出客人后黑屏 编辑:程序博客网 时间:2024/05/16 10:58

 

接口体中之宝含常量定义和方法声明两部分,并且默认都为public

接口实现为类定义,如果该类没有全部实现了接口的所有函数,则此类必须为abstract类,不能实例化对象

经过验证还发现,类似于继承,接口实现中也存在类中新添加的成员变量对接口的同名覆盖,将会加以证明。


形式:

interface Name

{

   public final DataType data1 = 常数1;

    ......

   public final DataType datan = 常数n;


   public ReturnType FuncName1(Paras....);

    ......

   public ReturnType FuncNamen(Paras....);

}


class One implements Name

{

    //实现所有方法

    //codes

}


abstract Two implements Name  //不可实例化对象

{

    //至少有一个方法没实现

    //codes

}

 

eg.

//桌面 interface1 2 3


//接口,只含常量和函数声明

interface Charge

{

    public final int max = 10;   //如果不加访问修饰符,默认为public

    public void Pay();

    public int Func();

}

 

//实现接口

class Car implements Charge

{

    protected int min;

    protected int max;        //和interface常量中同名的变量

    public Car(int min, int max)

    {

        this.min = min;        //成员

        this.max = max;      //经证明会发生同名覆盖     

    }

    //实现接口中函数1

    public void Pay()

    {

        System.out.println("class Car" + "  " + max);

    }  

    //实现接口中函数2

    public int Func()

    {

        //codes

        return -1;

    }

   //新增函数

    public void Show()

    {

        //该max为本类中的max,因为覆盖了接口中的max

        System.out.println("min = " + min + "  max = " + max );

    }

}

 

 

class Bus implements Charge

{

    public void Pay()

    {

        System.out.println("class Bus");

    }

    public int Func()

    {

        return 0;

    }

   //新增函数

    public void Show()

    {

        System.out.println("max = " + max );//该max为interface中常量max

    }

}

 

 

//该类只实现了接口两个函数中的其中一个,因此该类为abstract类,不能实例化对象

abstract class Taxi implements Charge

{

    public void Pay()

    {

        System.out.println("class Taxi");

    }

   //新增函数,由于本类为抽象类,所以无法实例化对象,也就无法调用次函数

    public void Show()

    {

        System.out.println("max = " + max );

    }

}

 

 

public class Sixth

{

    public static void main(String args[])

    {

        Car car = new Car(100, 200);

        car.Pay();

        car.Show();

        Bus bus = new Bus();

        bus.Pay();

        bus.Show();

        //不能用Taxi类实例化对象 

     }

}


运行结果

Java中接口interface和实现implements问题 - 大灰狼 - 大灰狼 的博客