在构造函数之前不执行静态块

时间:2017-02-15 04:33:21

标签: java

我遇到了一个问题。有三个班级 1.Teacher 2.TeacherEx 3.TeacherClass

我正在制作一个教师班public static Teacher t的静态对象 当我在TeacherEx中创建TeacherClass的4个对象时,TeacherEx中的静态块只执行一次,而它必须执行4次。 谁能解释一下究竟是什么问题?

发布所有3个班级 老师班

public class Teacher {
    public static String name;
    public static String subject;
    public static int  nolec;
}

public static class TeacherEx {

public int noStd;
public String place;
public static Teacher t;


public TeacherEx(int no, String p)
{
    noStd=no;
    place=p;

    t.name="prashantha";
    t.subject="Java_classes";
    t.nolec++;

    System.out.println("The nos of lec after creation class are "+t.nolec);

}


static{

    if(t==null)
    {
        t=new Teacher();
    }
    else
    {
        System.out.println("Nothing");
    }

    System.out.println("The nos of lec before this class creation are  "+t.nolec);
}

}


public class TeacherClass {

public static void main(String[] args)
{

    TeacherEx a=new TeacherEx(45,"banglore");

    TeacherEx b=new TeacherEx(75,"Mumbai");


    TeacherEx c=new TeacherEx(49,"chennai");

    TeacherEx d=new TeacherEx(47,"Newyork");

}

}

1 个答案:

答案 0 :(得分:1)

类的静态成员不是实例成员。这意味着它们被附加(绑定)到类本身而不是附加到类的实例。这里有4个TeacherEx类的实例,但这对静态成员无关紧要。即使您没有该类的任何实例,也可以访问static个成员。

亲自尝试:

public static void main(String[] args) {

    println(TeacherEx.t.toString());

}

当JVM在运行时初始化类时,将执行静态块。另一方面,在运行时执行实际实例化(new TeacherEx(...))时,将调用构造函数。