java 父类和子类

    public static void main(String[] args) {
        Father a=new Father();
        System.out.println("-----------");
        Child b=new Child();
        /**
         * Output:  I'm father
                    I'm child
                    可以看到在调用子类的构造方法时,如果不用super指定调用的父类构造方法
                    将自动隐式调用父类的默认无参构造方法
         */
        System.out.println("-----------");
        b.method();
    }
}
class Father{
    private String fathername="God";//对字段用priavte修饰符修饰,只能在本类中访问,体现了封装的特性
    /**
     * 事实上,private修饰的字段是可以被子类继承的,但是无法访问,相当于没有继承
     */
    Father(){//父类默认无参构造方法
        System.out.println("I'm father");
    }
    Father(String str){//显式写出父类有参构造方法
        System.out.println(str);
    }
    public void method(){
        System.out.println("I'm father method");
    }
}
class Child extends Father{
    private String fathername="kids";
    Child(){
        /**
         *  隐式调用了无参的父类构造方法
         */
        //super();//默认
        super("I'm explicit construction method ");//显式调用父类的参数类型为String的构造方法
        System.out.println("I'm child");
        System.out.println(fathername);//将调用
        //System.out.println(super.fathername);
        /**
         * 这样写任然不能访问父类的fathername字段,因为修饰符为private
         * 一般暴露set/get方法供外部访问
         */
    }
    public void method(){//覆盖父类的method()方法
        super.method();//调用父类发method
        System.out.println("I'm child method");
    }
原文地址:https://www.cnblogs.com/cnsec/p/13286828.html