接口java_Java 接口详解

35fdae7c617f9e427db672ab9ddd93db.png
interface People{
   void peopleList();
}
class Student implements People{
    public void peopleList(){
        System.out.println("I’m a student.");
    }
}
class Teacher implements People{
    public void peopleList(){
        System.out.println("I’m a teacher.");
    }	
}
public class Example{
    public static void main(String args[]){
    People a;             //声明接口变量
    a=new Student();      //实例化,接口变量中存放对象的引用
    a.peopleList();        //接口回调
    a=new Teacher();     //实例化,接口变量中存放对象的引用
    a.peopleList();       //接口回调
    }
}
结果:
I’m a student.
I’m a teacher.

接口是为了实现多态!

形式:接口 对象=new 实现类

为什么不直接创建实现类对象来调用方法呢?

原因:这就是java 多态的特点,使用父类引用指向子类对象,父类(接口)的引用就能够直接调用子类(实现类)的方法。

在实际的开发过程中之所以不直接创建实现类对象来调用方法,主要目的还是为了能够减少代码的修改量。

举个例子:

定义一个animal抽象类, 里面有两个方法。
接下里定义两个类(cat和dog)去继承animal,
cat和dog分别重写了animal中的方法。

我们在调用dog里面的方法之后,
想修改为调用cat的方法。 ----
只需要将Animal animal=new Dog()改成Animal
animal=new Catl(), 只改变了一个对象。
接着继续调用animal.sing(),animal.run()。
实际的开发过程中要维护大量的代码量,
如果要换一个对象,改的代码更少

//implA 为接口 ClassB为其实现类
implA A=new ClassB();//接口类型的引用变量A 去接收对象地址
or
ClassB A=new ClassB();//类类型的引用变量A 去接收对象地址

interface A { //接口A               
 //接口的方法声明必须是 public abstract ,即便不写默认也是
    public void fun();

}
public class B implements A {

    @Override
    public void fun() {
        //your coding
    }

}

如果我们要使用B类对象,调用B类方法,可以写

A demo = new B();

用接口类型的引用变量demo,去接收实现类B实例化出来的对象地址(这里的=是传递的地址)。

但是不是说使用

B demo=new B();

就不可以,也是可以的

但是!

为了代码修改方便,我们应该优先使用接口而不是类来引用对象,

但是必须保证存在适当的接口类型

public class InterfaceTest {

    public static void main(String[] args) {

        PetInterface p = new Cat();
        p.talk();
        p.batheSelf();//无法调用 ,报错The method batheSelf() is undefined for the type PetInterface
    }

}

interface PetInterface {                

    public void talk();

}

class Dog implements PetInterface {

    @Override
    public void talk() {
        System.out.println("Bark!");
    }

}

class Cat implements PetInterface {

    @Override
    public void talk() {
        System.out.println("Meow!");
    }

    public void batheSelf() {
        System.out.println("Cat bathing");
    }

}

我们看到,

方法batheSelf()仅仅存在实现类中时,

若我们仍然使用接口来引用对象时

PetInterface p = newCat(),

那些仅仅存在实现类中的方法,

是无法直接调用的即p.batheSelf()无法调用会报错。

所以这时使用Cat p = new Cat()即类来引用是更好的。

也就是说,我们应当优先使用接口类去引用对象,但是是有前提条件的,——也就是当实现类中全是接口类的方法的实现,没有自己单独的方法;当实现类中存在自己的方法时,使用实现类来声明对象。

多态的实现必须有三个条件

1:必须要有继承

2:必须要有重写

3:父类引用指向子类对象

上面三个条件缺一不可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值