关于接口的简单的介绍请看这篇文章(接口的简单介绍),本文将继续接着上篇对接口进行更加详细的讲解。
目录
一、接口的代码实现(简单接口回顾)
二、接口特性
接口是不能进行实例化的:
接口类型是一种引用类型,所以不能new
接口的对象。- 接口中的每个方法都是
public abstract
修饰的方法,接口中的方法都会被隐式的指定为public abstract
,也只能是被public abstract
修饰,使用其它的修饰符都会报错。 - 接口中的方法不能在接口中实现,只能在实现接口中的类进行实现,如果非要在接口中进行实现的话,该方法必须由
default
进行修饰。 - 子类实现接口中方法的时候,这个方法必须是由
public
进行修饰(因为接口中的抽象方法一定是由public abstract
进行修饰的)。 - 接口中可以含有变量,这个变量会被隐式的指定为
public static final
修饰。 - 接口中不能含有静态代码块和构造方法。
- 接口虽然不是类,但是接口编译完成后
字节码文件的后缀格式就是.class
- 如果类中没有实现接口中的所有抽象方法,则该类必须设置为抽象类(出来混迟早要还的)。
- jdb8中,接口中还可以包含
default
方法。
三、实现多个接口
下面来看多接口的代码:
interface IFlying {
void fly();
}
interface ISwimming {
void swim();
}
interface IRunning {
void run();
}
abstract class Animal {
public int age;
public String name;
public abstract void eat();
}
class Dog extends Animal implements IRunning,ISwimming {
@Override
public void eat() {
System.out.println(this.name + "正在吃狗粮");
}
@Override
public void run() {
System.out.println(this.name + "正在跑步");
}
@Override
public void swim() {
System.out.println(this.name + "正在狗刨式游泳");
}
}
好了,现在我们对上述代码进行拓展方便大家能够更好的进行理解,代码如下:
interface IFlying {
void fly();
}
interface ISwimming {
void swim();
}
interface IRunning {
void run();
}
abstract class Animal {
private int age;
private String name;
public abstract void eat();
public Animal(String name,int age) {
this.name = name;
this.age = 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;
}
}
class Dog extends Animal implements IRunning,ISwimming {
public Dog(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println(this.getName() + "正在吃狗粮");
}
@Override
public void run() {
System.out.println(this.getName() + "正在跑步");
}
@Override
public void swim() {
System.out.println(this.getName() + "正在狗刨式游泳");
}
}
class Bird extends Animal implements IFlying {
public Bird(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println(this.getName() + "正在吃鸟粮!");
}
@Override
public void fly() {
System.out.println(this.getName() + "正在用翅膀飞!");
}
}
class Robot implements IRunning {
@Override
public void run() {
System.out.println("机器人正在跑!");
}
} // Robot甚至不是动物,但是机器人会跑啊,所以我们依然可以结合IRunning()接口来进行使用。
public class Test {
public static void test1(Animal animal) {
animal.eat();
}
public static void test2(IFlying iFlying) {
iFlying.fly();
}
public static void testRun(IRunning iRunning) {
iRunning.run();
}
public static void testSwim(ISwimming iSwimming) {
iSwimming.swim();
}
public static void main(String[] args) {
test2(new Bird("小鸟3",3));
testRun(new Dog("小狗2",2));
testSwim((new Dog("小狗3",4)));
testRun(new Robot());
}
public static void main1(String[] args) {
test1(new Bird("小鸟1",3)); // 向上转型:父类引用引用了子类,子类中重写了父类中的抽象方法
test1(new Dog("小狗1",3)); // 向上转型:父类引用引用了子类,子类中重写了父类中的抽象方法
}
}
上述代码是java面向对象编程中最常见的一个用法:一个类继承父类,并且实现了多个接口。
四、接口间的继承(extends)
好了,以上就是Java中接口中最基本的内容了。就到这里吧,再见啦友友们!!!