Java-13 接口

接口

  • 接口本身是一个引用数据类型。

  • 定义接口格式:

interface 接口名()
  • 特点:
1.接口中只能定义抽象方法(1.8之前),所有的方法默认都是public abstract 修饰的
2.接口中只能定义常量,默认使用public static final 修饰的
3.接口不能创建对象,必须使用子类向上转型。接口的子类:实现接口的类。一个类可以实现多个接口
class 子类名 implements 接口1,接口2...{} //接口实现用implements
4.接口的子类要么实现接口中所有的抽象方法,要么自己是一个抽象类。
5.接口中没有构造方法。
6.接口只能继承接口,不能实现接口,可以多继承。
7.一个类可以在继承一个类的同时实现多个接口 继承要放到前面。
8.jdk8以后,可以在接口中定义已经实现的方法(有方法体),但是必须用static/default 修饰
    
  • 示例:
package Interface;

public class InterfaceDemo {
	public static void main(String[] args) {
		Fly f = new B();// 接口多态
	}
}

class C{
	
}

interface Fly{
	int a = 100;
	public void show();
	// jdk8以后,可以在接口中定义已经实现的方法
    // 用接口名调用
	public static void test() {
		
	}
    // 默认方法,使用子类调用
	public default void test2() {
		
	}
}

class B extends C implements Fly{
	public void show() {
		
	}
}


interface A extends Fly{
	
}
  • 接口示例2:
package Interface;

public class InterfaceTest {
	public static void main(String[] args) {
		InterB b = new Demo();// 接口的引用指向子类对象,接口多态
		b.watch();
		b.look();
	}
}

// InterA 接口包含一个抽象方法
interface InterA {
	int a = 1000;
	public abstract void look();
}
// 接口InterB继承接口InterA 自己内部实现一个抽象方法
interface InterB extends InterA{
	public abstract void watch();
}


class Test{
	
}
// Demo继承Test类,实现接口InterB
class Demo extends Test implements InterB{
	// 添加InterB的抽象方法watch,look
	public void watch() {
		System.out.println("watch");
	}
	public void look() {
		System.out.println("look");
	}
}
  • 抽象类和接口的区别:
1.一个类最多只能继承一个抽象类,但是可以实现多个接口。
2.抽象类中既可以定义变量也可以定义常量,接口中只能定义常量。
3.抽象类中既可以定义抽象方法,也可以定义非抽象方法,接口中能定义抽象方法(jdk1.8之前)
4.接口中没有构造方法,抽象类中有构造方法。
5.接口只能继承接口不能实现接口,可以多继承。
  • 练习1:
package Interface;
/*
 * 编写一个抽象类Animal 重选ing类中包括属性:name(String), 抽象方法:speak()
 * 编写一个宠物接口Pet,接口中包括方法:eat()   抽象
 * 再编写一个类Cat,继承抽象类实现接口,实现该接口和抽象类中的所有方法
 * 在main进行测试
 * */
public class InterfaceTest2 {
	public static void main(String[] args) {
		Pet p = new Cat("Tom");
		p.eat();
		// speak为子类独有方法,Pet接口中不存在。
		Animal a = new Cat("Tom");
		a.speak();
	}
}

interface Pet{
	abstract public void eat();
}


abstract class Animal{
	String name;
	abstract public void speak();
}

class Cat extends Animal implements Pet{
	public Cat() {}
	// 构造方法
	public Cat(String name) {
		this.name = name;
	}
	public void speak() {
		System.out.println(name + " is speak!");
	}
	public void eat() {
		System.out.println(name + " is eat!");
	}
}
  • 练习2:打印大小写
package Interface;

public class InterfaceTest3 {
	public static void main(String[] args) {
		InterfaceA a = new Print();
		InterfaceB b = new Print();
		a.printCapitalLetter();
		b.printLowercaseLetter();
	}
}


interface InterfaceA{
	void printCapitalLetter();
}

interface InterfaceB{
	void printLowercaseLetter();
}

class Print implements InterfaceA,InterfaceB{
	public void printCapitalLetter() {
		for (char i='A';i<='Z';i++) {
			System.out.println(i);
		}
	}
	public void printLowercaseLetter() {
		for (char i='a';i<='z';i++) {
			System.out.println(i);
		}
	}
}
原文地址:https://www.cnblogs.com/xujunkai/p/13766561.html