为了更多的清关。语法和示例
抽象类的语法
public abstract class MyAbstractClass
{
//code
public abstract void method();
}
抽象类的例子
public abstract class Animal
{
abstract void walk();
}
public class Dog extends Animal
{
void walk()
{
//Implementation is done here
}
}
接口语法
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
接口示例
interface Animal {
public void eat();
public void travel();
}
实现接口
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
扩展接口
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
扩展多个接口
public interface Hockey extends Sports, Event
扩展和实现两者
interface A can extends interface B
class A can extends class B
class A implements interface A
class A extends class B implements interface A