静态代码块、普通代码块、构造方法的执行顺序

静态代码块、普通代码块、构造方法的执行顺序,第1张

静态代码块、普通代码块、构造方法的执行顺序

直接上代码吧!!!

class Person{
    private String name;
    private boolean gender;
    private int age;
    private int id;
    static int count=-1;
    static {
        System.out.println("This is static initialization block");
    }

    {
        count++;
    }
    public Person() {
    id=count;
        System.out.println("This is initialization block, id is "+id);
        System.out.println("This is constructor");
    }

    public Person(String name, boolean gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        id=count;
        System.out.println("This is initialization block, id is "+id);

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Person [" +
                "name=" + name +
                ", age=" + age +
                ", gender=" + gender +
                ", id=" + id +
                "]";
    }
}
public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Person[] per = new Person[n];
        for (int i = 0; i < n; i++) {    //通过循环输入
            String name = scanner.next();
            int age = scanner.nextInt();
            boolean genter = scanner.nextBoolean();
            per[i] = new Person(name, genter, age);}
            for (int i = 0; i < n; i++) {
                System.out.println(per[per.length-i-1]);
            }

            Person person = new Person();
        System.out.println(person.getName()+","+person.getAge()+","+person.isGender()+","+person.getId());
            System.out.println(person);

    }
}

下面这是测试结果:

 静态代码块只会执行一次,普通代码块在对象创建之前执行,没创建一个对象前都会执行!!!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5563193.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存