13.5 抽象类和接口作为方法的参数与返回值

抽象类作为方法的参数:

//抽象类

abstract class Person{

    publicabstractvoid show();

}

class Student extends Person{

    @Override

    publicvoid show() {

        System.out.println("重写了show方法");

    }

}

//测试类

扫描二维码关注公众号,回复: 575692 查看本文章

publicclass Test {

    publicstaticvoid main(String[] args) {

        //通过多态的方式,创建一个Person类型的变量,而这个对象实际是Student

        Person p= new Student();

        //调用method方法

        method(p);

    }

    //定义一个方法method,用来接收一个Person类型对象,在方法中调用Person对象的show方法

    publicstaticvoid method(Person p){//抽象类作为参数

        //通过p变量调用show方法,这时实际调用的是Student对象中的show方法

        p.show();  

}

}


抽象类作为方法的返回值:

//抽象类

abstract class Person{

    public abstract void show();

}

class Student extends Person{

    @Override

    publicvoid show() {

        System.out.println("重写了show方法");

    }

}

//测试类

publicclass Test {

    publicstaticvoid main(String[] args) {

        //调用method方法,获取返回的Person对象

        Person p= method();

        //通过p变量调用show方法,这时实际调用的是Student对象中的show方法

        p.show();

    }

    //定义一个方法method,用来获取一个Person对象,在方法中完成Person对象的创建

    publicstatic Person method(){

        Person p= new Student();

        returnp;

    }

}


接口作为方法的参数:

//接口

interface Smoke{

    public abstract void smoking();

}

class Student implements Smoke{

    @Override

    publicvoid smoking() {

        System.out.println("饭后吸口烟,赛过活神仙");

    }

}

//测试类

publicclass Test {

    publicstaticvoid main(String[] args) {

        //通过多态的方式,创建一个Smoke类型的变量,而这个对象实际是Student

        Smoke s= new Student();

        //调用method方法

        method(s);

    }

    //定义一个方法method,用来接收一个Smoke类型对象,在方法中调用Smoke对象的show方法

    publicstaticvoid method(Smoke sm){//接口作为参数

        //通过sm变量调用smoking方法,这时实际调用的是Student对象中的smoking方法

        sm.smoking();

    }

}


接口作为方法的返回值:

//接口

interface Smoke{

    public abstract void smoking();

}

class Student implementsSmoke{

    @Override

    publicvoid smoking() {

        System.out.println("饭后吸口烟,赛过活神仙");

    }

}

//测试类

publicclass Test {

    publicstaticvoid main(String[] args) {

        //调用method方法,获取返回的会吸烟的对象

        Smoke s= method();

        //通过s变量调用smoking方法,这时实际调用的是Student对象中的smoking方法

        s.smoking();

    }

    //定义一个方法method,用来获取一个具备吸烟功能的对象,并在方法中完成吸烟者的创建

    publicstatic Smoke method(){

        Smoke sm= new Student();

        return sm;

    }

}


猜你喜欢

转载自blog.csdn.net/southdreams/article/details/80169077