您的位置:首页 > 编程语言 > Java开发

JAVA基础之接口

2015-10-06 09:58 711 查看

JAVA基础之接口

目录(?)[+]
抽象类和抽象方法
接口
完全解耦
Java的多重继承
通过继承来扩展接口
接口中的域
嵌套接口
接口与工厂


抽象类和抽象方法

抽象方法
仅有声明没有方法体

抽象类
包含抽象方法的类

如果一个类包含一个或多个抽象方法,那么该类必定是抽象类

如果继承一个抽象类,必须重写所有抽象方法,否则该子类也必须是抽象类

抽象类中可以包含非抽象方法

可以创建不包含任何抽象方法的抽象类

[java] view plaincopyprint?public class Test {  
    public static void main(String[] args) {  
        Super mSuper = new Sub();  
        mSuper.print(mSuper.getString());  
        mSuper.show();  
  
        Base mBase = new Child();  
        ((Child) mBase).function();  
    }  
}  
  
// 抽象类可以不包含抽象方法   
// 包含抽象方法一定是抽象类   
abstract class Base {}  
  
class Child extends Base {  
    void function() {  
        System.out.println("Child function");  
    }  
}  
  
abstract class Super {  
    abstract void print(String string);  
    abstract String getString();  
  
    void show() {  
        System.out.println("Super show");  
    }  
}  
  
// 继承抽象类需要重新所有抽象方法   
// 否则该类也必须是抽象类   
abstract class ASuper extends Super {}  
  
class Sub extends ASuper {  
    @Override  
    void print(String string) {  
        System.out.println(string + " print");  
    }  
  
    @Override  
    String getString() {  
        return "Sub";  
    }  
}  
  
/** 
输出如下:  
Sub print 
Super show 
Child function 
*/  
public class Test {
public static void main(String[] args) {
Super mSuper = new Sub();
mSuper.print(mSuper.getString());
mSuper.show();

Base mBase = new Child();
((Child) mBase).function();
}
}

// 抽象类可以不包含抽象方法
// 包含抽象方法一定是抽象类
abstract class Base {}

class Child extends Base {
void function() {
System.out.println("Child function");
}
}

abstract class Super {
abstract void print(String string);
abstract String getString();

void show() {
System.out.println("Super show");
}
}

// 继承抽象类需要重新所有抽象方法
// 否则该类也必须是抽象类
abstract class ASuper extends Super {}

class Sub extends ASuper {
@Override
void print(String string) {
System.out.println(string + " print");
}

@Override
String getString() {
return "Sub";
}
}

/**
输出如下:
Sub print
Super show
Child function
*/


接口

接口和内部类为我们提供了一种将接口和实现分离的更加结构化的方法

interface关键字
interface这个关键字产生一个完全抽象的类,它根本就没有提供任何具体实现

它允许创建者确定方法名、参数列表和返回类型,但是没有任何方法体

接口可以包含域,但这些域隐式地是static和final的

implements关键字
实现接口使用implement关键字

一个类可以实现多个接口,只能继承一个类(单继承,多实现)

[java] view plaincopyprint?public class Test {  
    // 策略模式   
    public static void ploy(Super s,int n) {  
        s.print(n);  
    }  
  
    public static void main(String[] args) {  
        Base mBase = new Sub();  
        mBase.function();  
  
        // Super对象就是一种策略   
        // Sub/Sub1 两种不同的策略应用到了int类型的num上   
        int num = 2;  
        ploy(new Sub(),num);  
        ploy(new Sub1(), num);  
    }  
}  
  
interface Base {  
    String string = "Base";  
  
    // 接口中方法默认是public的,即使不声明也是public的   
    public void function();   
}  
  
abstract class Super {  
    abstract void print(int num);  
    void show() {  
        System.out.println(getClass().getSimpleName() + " show");  
    }  
}  
  
class Sub extends Super implements Base {  
    @Override  
    void print(int num) {  
        //string = "Child"; 隐式是final的,不能修改   
        System.out.println(getClass().getSimpleName() + " " + num*100);  
    }  
  
    @Override  
    public void function() {  
        System.out.println("Sub function " + string);  
    }  
}  
  
class Sub1 extends Super {  
    @Override  
    void print(int num) {  
        System.out.println(getClass().getSimpleName() + " " + (num+100));  
    }  
}  
  
/** 
输出如下:  
Sub function Base 
Sub 200 
Sub1 102 
*/  
public class Test {
// 策略模式
public static void ploy(Super s,int n) {
s.print(n);
}

public static void main(String[] args) {
Base mBase = new Sub();
mBase.function();

// Super对象就是一种策略
// Sub/Sub1 两种不同的策略应用到了int类型的num上
int num = 2;
ploy(new Sub(),num);
ploy(new Sub1(), num);
}
}

interface Base {
String string = "Base";

// 接口中方法默认是public的,即使不声明也是public的
public void function();
}

abstract class Super {
abstract void print(int num);
void show() {
System.out.println(getClass().getSimpleName() + " show");
}
}

class Sub extends Super implements Base {
@Override
void print(int num) {
//string = "Child"; 隐式是final的,不能修改
System.out.println(getClass().getSimpleName() + " " + num*100);
}

@Override
public void function() {
System.out.println("Sub function " + string);
}
}

class Sub1 extends Super {
@Override
void print(int num) {
System.out.println(getClass().getSimpleName() + " " + (num+100));
}
}

/**
输出如下:
Sub function Base
Sub 200
Sub1 102
*/


完全解耦

将接口从具体实现中解耦使得接口可以应用于多种不同的具体实现

[java] view plaincopyprint?public class Test {  
    public static void main(String[] args) {  
        String input = "Test";  
        // 这里使用了适配器模式   
        // 将LowPass,HighPass,BandPass为Apply.process方法做适配   
        Apply.process(new FilterAdapter(new LowPass(1.0)), input);  
        Apply.process(new FilterAdapter(new HighPass(2.0)), input);  
        Apply.process(new FilterAdapter(new BandPass(1.0, 2.0)), input);  
    }  
}  
  
interface Processor {  
    String name();  
    Object process(Object input);  
}  
  
class Apply {  
    public static void process(Processor s, Object o) {  
        System.out.println(s.process(o));  
    }  
}  
  
// FilterAdapter使用了代理   
// 实际上是Filter的代理   
class FilterAdapter implements Processor {  
    Filter mFilter;  
  
    public FilterAdapter(Filter mFilter) {  
        this.mFilter = mFilter;  
    }  
  
    public String name() {  
        return mFilter.name();  
    }  
  
    public Object process(Object input) {  
        return mFilter.process((String) input);  
    }  
}  
  
class Filter {  
    String name() {  
        return getClass().getSimpleName();  
    }  
  
    public String process(String input) {  
        return input;  
    }  
}  
  
class LowPass extends Filter {  
    double cutoff;  
  
    public LowPass(double cutoff) {  
        this.cutoff = cutoff;  
    }  
  
    public String process(String input) {  
        return input + " " + cutoff;  
    }  
}  
  
class HighPass extends Filter {  
    double cutoff;  
  
    public HighPass(double cutoff) {  
        this.cutoff = cutoff;  
    }  
  
    public String process(String input) {  
        return input + " " + cutoff;  
    }  
}  
  
class BandPass extends Filter {  
    double lowCutoff, highCutoff;  
  
    public BandPass(double lowCutoff, double highCutoff) {  
        this.lowCutoff = lowCutoff;  
        this.highCutoff = highCutoff;  
    }  
  
    public String process(String input) {  
        return input + " " + lowCutoff + " " + highCutoff;  
    }  
}  
public class Test {
public static void main(String[] args) {
String input = "Test";
// 这里使用了适配器模式
// 将LowPass,HighPass,BandPass为Apply.process方法做适配
Apply.process(new FilterAdapter(new LowPass(1.0)), input);
Apply.process(new FilterAdapter(new HighPass(2.0)), input);
Apply.process(new FilterAdapter(new BandPass(1.0, 2.0)), input);
}
}

interface Processor {
String name();
Object process(Object input);
}

class Apply {
public static void process(Processor s, Object o) {
System.out.println(s.process(o));
}
}

// FilterAdapter使用了代理
// 实际上是Filter的代理
class FilterAdapter implements Processor {
Filter mFilter;

public FilterAdapter(Filter mFilter) {
this.mFilter = mFilter;
}

public String name() {
return mFilter.name();
}

public Object process(Object input) {
return mFilter.process((String) input);
}
}

class Filter {
String name() {
return getClass().getSimpleName();
}

public String process(String input) {
return input;
}
}

class LowPass extends Filter {
double cutoff;

public LowPass(double cutoff) {
this.cutoff = cutoff;
}

public String process(String input) {
return input + " " + cutoff;
}
}

class HighPass extends Filter {
double cutoff;

public HighPass(double cutoff) {
this.cutoff = cutoff;
}

public String process(String input) {
return input + " " + cutoff;
}
}

class BandPass extends Filter {
double lowCutoff, highCutoff;

public BandPass(double lowCutoff, double highCutoff) {
this.lowCutoff = lowCutoff;
this.highCutoff = highCutoff;
}

public String process(String input) {
return input + " " + lowCutoff + " " + highCutoff;
}
}


Java的多重继承

在导出类中,只能继承一个类,可以实现多个接口

接口可以继承接口,并且可以同时继承多个接口

使用接口的原因
1.为了能够向上转型为多个基本类型
2.防止客户端程序员创建该类的对象

[java] view plaincopyprint?public class Test {  
    public static void main(String[] args) {  
        CanFly Hero1 = new Hero();  
        Hero1.fly();  
  
        CanSwim hero2 = new Hero();  
        hero2.swim();  
  
        CanFight hero3 = new Hero();  
        hero3.fight();  
  
        Super hero4 = new Hero();  
        hero4.superSkill();  
        hero4.swim();  
        hero4.fight();  
  
        Action hero5 = new Hero();  
        hero5.action();  
    }  
}  
  
interface CanFly {  
    void fly();  
}  
  
interface CanSwim {  
    void swim();  
}  
  
interface CanFight {  
    void fight();  
}  
  
//接口可以多继承   
interface Super extends CanFight, CanSwim {  
    void superSkill();  
}  
  
abstract class Action {  
    abstract void action();  
}  
  
class NewAction extends Action {  
    @Override  
    void action() {}  
}  
  
// 只能继承一个类,可以实现多个接口   
class Hero extends NewAction implements CanFly, Super {  
    public void fight() {}  
    public void swim() {}  
    public void fly() {}  
    public void superSkill() {}  
  
    @Override  
    void action() {}  
}  
public class Test {
public static void main(String[] args) {
CanFly Hero1 = new Hero();
Hero1.fly();

CanSwim hero2 = new Hero();
hero2.swim();

CanFight hero3 = new Hero();
hero3.fight();

Super hero4 = new Hero();
hero4.superSkill();
hero4.swim();
hero4.fight();

Action hero5 = new Hero();
hero5.action();
}
}

interface CanFly {
void fly();
}

interface CanSwim {
void swim();
}

interface CanFight {
void fight();
}

//接口可以多继承
interface Super extends CanFight, CanSwim {
void superSkill();
}

abstract class Action {
abstract void action();
}

class NewAction extends Action {
@Override
void action() {}
}

// 只能继承一个类,可以实现多个接口
class Hero extends NewAction implements CanFly, Super {
public void fight() {}
public void swim() {}
public void fly() {}
public void superSkill() {}

@Override
void action() {}
}


通过继承来扩展接口

组合接口时的名字冲突
[java] view plaincopyprint?interface CanFly {  
    void fly();  
}  
  
class SuperMan {  
    int fly() {return 1;}  
}  
  
// 编译报错   
// The return types are incompatible for the inherited methods CanFly.fly(), SuperMan.fly()   
class Hero extends SuperMan implements CanFly {}  
interface CanFly {
void fly();
}

class SuperMan {
int fly() {return 1;}
}

// 编译报错
// The return types are incompatible for the inherited methods CanFly.fly(), SuperMan.fly()
class Hero extends SuperMan implements CanFly {}
[java] view plaincopyprint?public class Test {  
    public static void main(String[] args) {  
        Hero hero = new Hero();  
        hero.fly();  
    }  
}  
  
interface CanFly {  
    void fly();  
}  
  
class SuperMan {  
    public void fly() {  
        System.out.print("SuperMan");  
    }  
}  
  
// 编译不会报错,因为SuperMan的fly()会被作为CanFly.fly()的实现   
class Hero extends SuperMan implements CanFly {}  
public class Test {
public static void main(String[] args) {
Hero hero = new Hero();
hero.fly();
}
}

interface CanFly {
void fly();
}

class SuperMan {
public void fly() {
System.out.print("SuperMan");
}
}

// 编译不会报错,因为SuperMan的fly()会被作为CanFly.fly()的实现
class Hero extends SuperMan implements CanFly {}


接口中的域

接口中的任何域都自动是static和final的

初始化接口中的域
接口中的域需要显示的初始化

接口中定义的域不能是“空final”,但是可以被非常量表达式初始化

[java] view plaincopyprint?interface Processor {  
    // 必须显式初始化   
    int CORE = 8;  
    // 可以以非常量表达式初始化   
    int THREAD = new Random().nextInt();  
}  
interface Processor {
// 必须显式初始化
int CORE = 8;
// 可以以非常量表达式初始化
int THREAD = new Random().nextInt();
}


嵌套接口

接口可以嵌套在类和其他接口中

接口也可以被实现为private

[java] view plaincopyprint?public class Test {  
    public static void main(String[] args) {  
        Skill skill = new Skill();  
        // The type Skill.IFight is not visible   
        //Skill.IFight fight = skill.getFight();   
  
        // The type Skill.IFight is not visible   
        //skill.getFight().fight();   
  
        skill.setFight(new Skill().getFight());  
    }  
}  
  
class Skill {  
    interface IRun {  
        void run();  
    }  
  
    public interface IEat {  
        void eat();  
    }  
  
    // private接口不能在定义它的类之外被实现   
    private interface IFight {  
        void fight();  
    }  
  
    public class Run implements IRun {  
        @Override  
        public void run() {}  
    }  
  
    // 接口也可以被实现为private   
    private class Eat implements IEat {  
        @Override  
        public void eat() {}  
    }  
  
    // private 接口可以被实现为public   
    public class Fight implements IFight {  
        @Override  
        public void fight() {  
            System.out.print("fighting!");  
        }  
    }  
  
    public IFight getFight() {  
        return new Fight();  
    }  
  
    private IFight fighter;  
  
    public void setFight(IFight fight) {  
        fighter = fight;  
        fighter.fight();  
    }  
}  
  
interface ISuperMan {  
    // 接口中可以嵌套接口   
    // 自动为public,添加public是多余的   
    interface IFly {  
        void fly();  
    }  
  
    void savePerson();  
}  
  
class Boss {  
    class Run implements Skill.IRun {  
        @Override  
        public void run() {}  
    }  
  
    class Eat implements Skill.IEat {  
        @Override  
        public void eat() {}  
    }  
  
    class SuperMan implements ISuperMan {  
        @Override  
        public void savePerson() {}  
  
        class Fly implements ISuperMan.IFly {  
            @Override  
            public void fly() {}  
        }  
    }  
  
    class FlyImpl implements ISuperMan.IFly {  
        @Override  
        public void fly() {}  
    }  
}  
/** 
输出如下:  
fighting! 
*/  
public class Test {
public static void main(String[] args) {
Skill skill = new Skill();
// The type Skill.IFight is not visible
//Skill.IFight fight = skill.getFight();

// The type Skill.IFight is not visible
//skill.getFight().fight();

skill.setFight(new Skill().getFight());
}
}

class Skill {
interface IRun {
void run();
}

public interface IEat {
void eat();
}

// private接口不能在定义它的类之外被实现
private interface IFight {
void fight();
}

public class Run implements IRun {
@Override
public void run() {}
}

// 接口也可以被实现为privateprivate class Eat implements IEat {
@Override
public void eat() {}
}

// private 接口可以被实现为public
public class Fight implements IFight {
@Override
public void fight() {
System.out.print("fighting!");
}
}

public IFight getFight() {
return new Fight();
}

private IFight fighter;

public void setFight(IFight fight) {
fighter = fight;
fighter.fight();
}
}

interface ISuperMan {
// 接口中可以嵌套接口
// 自动为public,添加public是多余的
interface IFly {
void fly();
}

void savePerson();
}

class Boss {
class Run implements Skill.IRun {
@Override
public void run() {}
}

class Eat implements Skill.IEat {
@Override
public void eat() {}
}

class SuperMan implements ISuperMan {
@Override
public void savePerson() {}

class Fly implements ISuperMan.IFly {
@Override
public void fly() {}
}
}

class FlyImpl implements ISuperMan.IFly {
@Override
public void fly() {}
}
}
/**
输出如下:
fighting!
*/


接口与工厂

接口是实现多重继承的途径

[java] view plaincopyprint?public class Test {  
    public static void main(String[] args) {  
        Games.GameConsumer(new CheckersFactory());  
        Games.GameConsumer(new ChessFactory());  
    }  
}  
  
// 使用了工厂模式   
interface IGame {  
    boolean move();  
}  
  
interface IGameFactory {  
    IGame getGame();  
}  
  
class Checkers implements IGame {  
    @Override  
    public boolean move() {  
        System.out.println("Checkers move");  
        return true;  
    }  
}  
  
class Chess implements IGame {  
    @Override  
    public boolean move() {  
        System.out.println("Chess move");  
        return true;  
    }  
}  
  
class CheckersFactory implements IGameFactory {  
    @Override  
    public IGame getGame() {  
        return new Checkers();  
    }  
}  
  
class ChessFactory implements IGameFactory {  
    @Override  
    public IGame getGame() {  
        return new Chess();  
    }  
}  
  
// 不同类型的游戏都可以复用这段代码   
class Games {  
    public static void GameConsumer(IGameFactory factory) {  
        IGame game = factory.getGame();  
        game.move();  
    }  
}  
/** 
输出如下:  
Checkers move 
Chess move 
*/  
public class Test {
public static void main(String[] args) {
Games.GameConsumer(new CheckersFactory());
Games.GameConsumer(new ChessFactory());
}
}

// 使用了工厂模式
interface IGame {
boolean move();
}

interface IGameFactory {
IGame getGame();
}

class Checkers implements IGame {
@Override
public boolean move() {
System.out.println("Checkers move");
return true;
}
}

class Chess implements IGame {
@Override
public boolean move() {
System.out.println("Chess move");
return true;
}
}

class CheckersFactory implements IGameFactory {
@Override
public IGame getGame() {
return new Checkers();
}
}

class ChessFactory implements IGameFactory {
@Override
public IGame getGame() {
return new Chess();
}
}

// 不同类型的游戏都可以复用这段代码
class Games {
public static void GameConsumer(IGameFactory factory) {
IGame game = factory.getGame();
game.move();
}
}
/**
输出如下:
Checkers move
Chess move
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: