java基础

java中的接口

2019-02-26  本文已影响0人  小漫画ing

接口的特点:

A:接口用关键字interface表示;
格式:interface 接口名{}
B:类实现接口用implements表示;
格式:class 类名 implements 接口名 {}
定义一个动物培训的接口:

interface AnimalTrain{
    public abstract void jump();
}

C:接口不能实例化;
按照多态的方式,由具体的子类实例化。其实这也是多态的一种,接口多态。

D:接口的子类
要么是抽象类
要么重写接口中的所有抽象方法
抽象类实现接口(这样的意义不大):

abstract class Dog implements AnimalTrain{
    //因为AnimalTrain类中得jump()方法是抽象的,所以这里定义为抽象类;
}

具体类实现接口:

class Cat implements AnimalTrain{
     public abstract void jump(){
          System.out.println("猫可以跳高");
      }
}
class InterfaceDemo{
  public static void main (String[] args){
      AnimalTrain at=new Cat();
      at.jump();//猫可以跳高
}
}

接口的成员特点:

A:成员变量
接口中的变量是常量,并且是静态的,默认的。

package cn.manman.com;
interface Inter{
    public int num=10;
    public final int num2=20;
    
}
class InterImpl implements Inter{
    
}
public class jiekou {
    public static void main(String[] args) {
        Inter inter=new InterImpl();
        System.out.println(inter.num);
        System.out.println(inter.num2);
    }
}

结果

B:成员方法
接口的方法必须是抽象的,默认修饰符是public abstract;

abstract void show();//默认是public
public void show1();//默认抽象

C:构造方法
接口没有构造方法;

类与类,类与接口,接口与接口

练习:

1、猫狗案例,加入跳高的额外功能

package cn.manman.com;
//定义抽象类

abstract class Anmail{
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    private String name;
    public Anmail(){};
    public Anmail(int age,String name){
        this.age=age;
        this.name=name;
    }
    //睡觉
    public void sleep(){
        
    }
    //吃饭
    public abstract void eat();
    
}
//定义跳高接口
interface jump{
    public abstract void jump();
}
//具体猫类
 class Cat2 extends Anmail{
    public Cat2(){};
    public Cat2(int age,String name){
        super(age,name);
    }
    public void eat(){
        System.out.println("猫吃鱼");
    }
    
}
//具体狗类
class Dog2 extends Anmail{
    public Dog2(){};
    public Dog2(int age,String name){
        super(age,name);
    }
    public void eat(){
        System.out.println("狗吃骨头");
    };
}
//有跳高功能的猫
class CatJump extends Cat2 implements jump{
    public CatJump(){};
    public CatJump(int age,String name){
        super(age,name);
    }
    public void jump(){
        System.out.println("猫可以跳高");
    };
}

//有跳高功能的狗
class DogJump extends Dog2 implements jump{
    public DogJump(){};
    public DogJump(int age,String name){
        super(age,name);
    }
    public void jump(){
        System.out.println("猫可以跳高");
    };
}
public class anli_maogou {
    public static void main(String[] args) {
        CatJump catJump=new CatJump();
        catJump.setAge(10);
        catJump.setName("小漫画");
        System.out.println("猫的名字是:"+catJump.getName()+","+"年龄是:"+catJump.getAge());
        catJump.eat();
        catJump.jump();
    }
}

结果
上一篇 下一篇

猜你喜欢

热点阅读