类的加载顺序

来源:互联网 发布:软件联盟 编辑:程序博客网 时间:2024/05/11 01:20
class Base {    private String nameBase = "base";    public Base() {        System.out.println("nameBase="+nameBase);        System.out.println("this is Base");        tellName();        printName();    }    public void tellName() {        System.out.println("Base tell name: "+nameBase);    }    public void printName() {        System.out.println("Base print name: "+nameBase);    }}public class Dervied extends Base{    private String name = "derived";    public Dervied() {        System.out.println("this is Derived");        tellName();        printName();    }    public void tellName() {        System.out.println("Dervied tell name: "+name);    }   /* public void printName() {        System.out.println("Dervied print name:"+name);    }*/    public static void main(String[] args) {        new Dervied();    }}


nameBase=basethis is BaseDervied tell name: nullBase print name: basethis is DerivedDervied tell name: derivedBase print name: base

class ParentClass {    public static int a = 2; //必须放到静态代码块前面    //public int a = 2;    public int b = 3; // 必须放到匿名代码块的前面,以保证先被初始化后使用    private String str="ParentClass";    {        System.out.println("this is anonymity b="+b+", str = "+str);    }    static {        a = 4;        System.out.println("this is static and a="+a);    }    public void s() {        System.out.println("this is parent");    }    public ParentClass() {        System.out.println("b="+b);        System.out.println("this is parent gozao");        s();    }}public class Sons extends ParentClass{   public Sons() {       System.out.println("this is Sons gozao");    }    public void s() {        System.out.println("this is son");    }    public static void main(String[] args) {        ParentClass d = new Sons();        d.s(); //在父类中通过this.s()调用的是子类的方法,子类的s()方法覆盖了父类的方法后,无论在哪里调用,都是调用子类的方法。    }}/*    类内的加载顺序为:        静态变量        静态代码块        静态方法        匿名代码块        非静态变量        构造函数 */


0 0
原创粉丝点击