天天看點

抽象類、接口、多态特性

1. 抽象類本身不能被執行個體化,可以沒有抽象方法

2. 父類與接口有相同的方法時,不會産生沖突,因為隻會有一份方法的實作

3, 将Fight接口的canFight方法傳回值改為int,此時編譯報錯

      a)錯誤:The return types are incompatible for the inherited methods Fight.canFight(), Super.canFight()

package com.yjq.cn.interface

public abstract class AbstractTest {
	int i = 10;
	
	public static int f(int i) {
		return ++i;
	}
	
	//無法被調用
	public void f1() {
		System.out.println("f1");
	}
	
	public static void main(String[] args) {
		//抽象類可以沒有抽象方法
		System.out.println("抽象類,應用于不需要産生執行個體場景:" + AbstractTest.f(10));
		System.out.println("---------------");
		RealSuper rs = new RealSuper();
		((Fly)rs).canFly();
		//父類與實作接口重方法名稱
		((Fight)rs).canFight();
		((Super)rs).canFight();
		
	}
}

interface Fly {
	void canFly();
}

interface Swim {
	void canSwim();
}

interface Fight {
	void canFight();   //戰鬥方法1
}

class Super {
	//戰鬥方法2
	public void canFight() {  
		System.out.println("super.fight()");
	}
}

class RealSuper extends Super implements Fly, Swim, Fight {

	@Override
	public void canFly() {
		System.out.println("RealSuper.canFlay()");
	}	

	@Override
	public void canSwim() {
		System.out.println("RealSuper.canSwim()");
	}
	
}
           

//output

抽象類,應用于不需要産生執行個體場景:11

---------------

RealSuper.canFlay()

super.fight()

super.fight()

繼續閱讀