JAVA_learning11

interface(接口)

java只支持单继承
接口帮助我们实现多继承——一个类可以实现多个接口  
接口是一种特殊的抽象类
抽象类中所有方法都是抽象方法,所有成员变量都是静态成员变量
但是这个抽象类不用写abstract,抽象方法也不用写abstract ,因为interface中只能定义抽象方法
interface中声明的属性默认为 public static final,也只能是这个
interface中只能定义抽象方法,默认且只能为public

public interface Runner{
	public static final int id = 1;//int id = 1; 

	public void start();
	public void run();
	public void stop();
} 

example

interface Singer{
	public void sing();
	public void sleep();
}

class Student implements Singer{//这里不是extends,而是implements,但是可以看做继承
	private String name;
	Student(String name){
		this.name = name;
	}
	
	public void study(){
		System.out.println("studying");
	}
	
	public String getName(){
		return name;
	}

	public void sing() {//方法重写
		System.out.println("Student is studying");
	}

	public void sleep(){
		System.out.println("Stdent is sleeping");
	}
}

interface Painter{
	public void paint();
	public void eat();
} 

class Teacher implements Singer, Painter{//这里不是extends,而是implements,但是可以看做继承
	private String name;
	Teacher(String name){
		this.name = name;
	}
	
	public void teach(){
		System.out.println("teaching");
	}
	
	public String getName(){
		return name;
	}

	public void sing() {//方法重写
		System.out.println("Teacher is studying");
	}

	public void sleep(){
		System.out.println("Teacher is sleeping");
	}

	public void paint(){
		System.out.println("Teacher is painting");
	}

	public void eat(){
		System.out.println("Teacher is eating");
	}
}

public class Test{
	public static void main(String args[]){
		Singer s1 = new  Student("le");//new出来的Student中包含 name, study(), sing(), sleep(),但是,就像对象转型中,父类引用指向子类对象,实际上指向父类
		s1.sing();
		s1.sleep(); 
		//s1.study();
		Singer s2 = new Teacher("LE");
		s2.sing();
		s2.sleep();
		//s2.paint();
		//s2.eat();
		/s2.teach();
		Painter p1 = (Painter) s2;
		p1.paint();
		p1.eat();
	}
}

图1

example

abstract class Animal{
	private String name;
	abstract void enjoy();
}

interface Protectable{
	public void beProtectable();
}

interface Valueable{
	public double getMoney();
}

interface A extends Protectable{//接口之间可以相互继承
	 void m();
}

class GoldMoney extends Animal implements Protectable, Valueable{
	public void beProtectable(){
		System.out.println("live in the room");
	}

	public double getMoney(){
		return 10000;
	}

	public void enjoy(){
		System.out.println("~~叫");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值