Java类实例化的顺序

package org.whb.test.demo805;


/*
一.java类实例化的顺序:

父类:static{}(无名称方法体)

子类:static{}(无名称方法体)

父类:{}(无名方法体)

父类 构造函数

子类 {}(无名方法体)

子类 构造行数

二.静态方法/变量使用的场合

1,当多个对象共享某个变量或者方法时

测试代码,输出的结果一目了然

*/

class A{
    protected static String name = "jessie";
    static{
        System.out.println("static none name method of super(A) class");
          }
    {
        System.out.println("none name method of super(A)");
    }
    public A(){
        System.out.println("constructor of super(A)");
               }
    protected static void getName()
    {
       
        System.out.println(name); 
    }
   
    protected static void setName(String pname)
    {
        name = pname;
        System.out.println(name); 
    }
}
class B extends A{
    static{
        System.out.println("static none name method of sub(B) class");
    }
   
    {
        System.out.println("none name method of sub(B) class");
    }
    public B(){
        System.out.println("constructor sub(B)");
    }  
}

class C extends B{

    public C(){
        System.out.println("constructor of sub class(C)");
    } 

   
}
public class Test01{
    public static void main(String[] ars)throws Exception{
        A ab = new B();
        System.out.println("**************************");
        ab = new B();
        System.out.println("**************************");
        B BTest = new B();
        System.out.println("**************************");
        C CTest = new C();
        System.out.println("**************************");
        CTest.getName();
        CTest.setName("shirley");
        BTest.getName();
        CTest.getName();
    }
}
 

 

结果:

static none name method of super(A) class
static none name method of sub(B) class
none name method of super(A)
constructor of super(A)
none name method of sub(B) class
constructor sub(B)
**************************
none name method of super(A)
constructor of super(A)
none name method of sub(B) class
constructor sub(B)
**************************
none name method of super(A)
constructor of super(A)
none name method of sub(B) class
constructor sub(B)
**************************
none name method of super(A)
constructor of super(A)
none name method of sub(B) class
constructor sub(B)
constructor of sub class(C)
**************************
jessie
shirley
shirley
shirley

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值