代码详解のJava面向对象特性之多态

来源:互联网 发布:免费的会计软件 编辑:程序博客网 时间:2024/06/07 06:14

一、main函数

package com.sdmjhca.springBootDemo.duotai;/** * @author JHMI on 2017/8/20 0020. * java面向对象的特性之多态 * 特性1、继承 * 2、子类重写父类方法 * 3、父类的引用指向子类实例 * 4father对象只能访问父类中声明方法,不能调用子类中新增的方法、以及定义为私有的方法 */public class Main {    public static void main(String args[]){        Father father = new Son();        /*father.publicMethod("test");        father.protectedMethod("test");        //此处父类对象无法访问子类中的protected修饰的重载方法        new Son().protectedMethod("test","test2");        new Son().publicMethod("","");*/        //father.finalMethod();    }}
二、父类

package com.sdmjhca.springBootDemo.duotai;/** * @author JHMI on 2017/8/20 0020. * 父类中的方法区分 * 1public 的方法可以被重写 * 2private的方法对子类不可见,不能被重写 * 3protected的方法可以被重写,但是对包外不可见 * 4static修饰的方法标识这个方法是类方法,不能被重写 * 5final修饰的方法,标识这个方法不能被重写,但是可以重载 */public  class Father {    public Father(){        publicMethod("father");        privateMethod("ffff");        protectedMethod("aaaaaaaaa");        staticMethod();        finalMethod();    }    public void publicMethod(String s){        System.out.println("-------------公有父类方法---"+s);    }    private void privateMethod(String s){        System.out.println("--------------------私有父类方法---"+s);    }    protected void protectedMethod(String s){        System.out.println("------------受保护的父类方法---"+s);    }     //abstract void method();    public static void staticMethod(){        System.out.println("=-----父类静态方法----");    }    public final void finalMethod(){        System.out.println("=--------------父类final方法");    }}
三、子类

package com.sdmjhca.springBootDemo.duotai;/** * @author JHMI on 2017/8/20 0020. */public class Son  extends Father{    public Son(){        System.out.println("-----------转到子类构造方法------");    }    /**     * 重写父类的公有方法     * @param s     */    @Override    public void publicMethod(String s){        System.out.println("---------------重写父类公有方法="+s);    }    public void publicMethod(String s,String ss){        System.out.println("---------------重载父类公有方法="+s+"---"+ss);    }    private void privateMethod(String s){        System.out.println("---------------重写父类私有方法="+s);    }    private void privateMethod(String s,String ss){        System.out.println("---------------重载父类私有方法="+s+"------"+ss);    }    /**     * protected的方法可以被重写 和 重载,但是只对包内部的类可见,对外不可见     * @param s     */    protected void protectedMethod(String s){        System.out.println("------------重写受保护的父类方法---"+s);    }    protected void protectedMethod(String s,String ss){        System.out.println("------------重载受保护的父类方法---"+s+"---"+ss);    }    public static void staticMethod(){        System.out.println("=-----重写父类静态方法----");    }    public  void finalMethod(String ss){        System.out.println("------------重写父类final方法,直接编译错误,但是可以重载-----");    }}

参考文章:http://www.cnblogs.com/xrq730/p/4820237.html