接口
接口
参考黑马程序员
接口的概述
接口就是一种公共的规范标准,只要符合规范标准,大家都可以通用
Java中的接口更多的体现在对行为的抽象
接口的特点
-
接口用关键字interface修饰
public interface 接口名{}
-
类实现接口用implements表示
public class 类名 implements 接口名{}
-
接口不能实例化
接口如何实例化呢?参照多态的方式,通过实现类对象实例化,这叫接口多态。
多态形式:具体类多态,抽象类多态,接口多态。
多态的前提:有继承或者实现关系;有方法的重写;有父(类/接口)引用指向(子/实现)类对象。
-
接口的实现类
要么重写接口中的所有抽象方法
要么是抽象类
接口的成员特点
-
成员变量
只能是常量
默认修饰符:public static final
-
构造方法
接口没有构造方法,因为接口主要是对行为进行抽象的,是没有具体存在
一个类如果没有父类,默认继承自Object类
-
成员方法
只能是抽象方法
默认修饰符:public abstract
代码
Jumpping接口
public interface Jumpping {
public abstract void jump();
}
Animal抽象类
public abstract class Animal {
private String name;
private int age;
public Animal() {
}
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public abstract void eat();
}
Cat类
public class Cat extends Animal implements Jumpping{
public Cat() {
}
public Cat(String name, int age) {
super(name, age);
}
测试类
/*
测试类
*/
public class AnimalDemo {
public static void main(String[] args) {
//创建对象,调用方法
Jumpping j = new Cat();
j.jump();
System.out.println("------------------");
Animal a = new Cat();
a.setAge(5);
a.setName("加菲");
System.out.println(a.getName()+","+a.getAge());
a.eat();
// a.jump();
a = new Cat("kuli",30);
System.out.println(a.getName()+","+a.getAge());
a.eat();
System.out.println("------------------");
Cat c = new Cat();
c.setAge(5);
c.setName("加菲");
System.out.println(c.getName()+","+c.getAge());
c.eat();
c.jump();
}
}

浙公网安备 33010602011771号