Java4Android基础学习之面向对象应用

  其实这里说的应用只是利用前面学过的知识综合起来,模拟一个非常简单的项目——打印机。

1、先是做一个打印机打印,

public class father {
    void turn_on(){
        System.out.println("turn on");
    }

    void turn_off(){
        System.out.println("turn off");
    }

    void  print(String s){
        System.out.println("print " + s);
    }
}
public class test {
    public static void main(String args []){
        father p = new father();

        p.turn_on();
        p.print("a");
        p.turn_off();
    }
}

这样很简单就实现了开机,关机,打印

2、然后是增加了打印机的个数;

  1)这里就使用继承,因为如果一个打印机写一个类的话,那将产生很多重复代码(不管什么打印机都有开机,关机,打印这几个功能);

  2)每个打印机的类里面写他特有的方法,若父类中继承来的方法不满足要求的话,就在子类中重写,利用 super来调用父类中的函数;

  如:

//父类
public class father {
    void turn_on(){
        System.out.println("turn on");
    }

    void turn_off(){
        System.out.println("turn off");
    }

    void  print(String s){
        System.out.println("print " + s);
    }
}
//打印机1
public class hpprint extends father{

}
//打印机2
public class canno extends father{
    void clean(){
        System.out.println("Clean");
    }

    void turn_off(){
        this.clean();
        super.turn_on();
    }
}
//主函数
public class test {
    public static void main(String args []){
        father p = new father();

        p.turn_on();
        p.print("a");
        p.turn_off();
    }
}

这样的话就能减少很多重复代码,试想下,如果有十台打印机的话,就比每个类里都写开机,关机这些函数效率要高得多多的了。

 

  这个模拟的项目正好把前面学到的知识都联系起来了,再次回顾了一篇,加深印象。

posted @ 2016-09-20 20:46  yiwp  阅读(183)  评论(0编辑  收藏  举报