F
F
Fedor unknown2020-09-29 17:52:19
Java
Fedor unknown, 2020-09-29 17:52:19

Why methods do not read data?

Hello!
there are two classes:

public class Student {
    private String name;
    private String secondName;
    private int age;

    private String format = ("Меня зовут %s %s и мне %s лет");
    private String info = String.format(format,name,secondName,age);

    public void personInfo(){
        System.out.println(info);
    }

    public Student(String name, String secondName, int age) {
        this.name = name;
        this.secondName = secondName;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {

        Student person1 = new Student("ПЕТЯ", "Сидоров", 22);
        person1.personInfo();

    }
}

It became curious why the method does not read data from the constructor?
And how is it done right?

Ps Just started to learn please do not pour shit)))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2020-09-29
@turdubekov

At the language level, there is a declaration of fields with initialization, but not at the bytecode level. The compiler moves all initialization operations to the beginning of the declared constructor or to the default constructor. Accordingly, your code after compilation will correspond to the following:

public class Student {
    private String name;
    private String secondName;
    private int age;

    private String format;
    private String info;

    public void personInfo(){
        System.out.println(info);
    }

    public Student(String name, String secondName, int age) {
        this.format = ("Меня зовут %s %s и мне %s лет");
        this.info = String.format(format,name,secondName,age);

        this.name = name;
        this.secondName = secondName;
        this.age = age;
    }
}

This means that at the time of execution String.format(format,name,secondName,age), the fields will contain null.

P
Pavel Shvedov, 2020-09-29
@mmmaaak

I guess the value of info is calculated before the body of the constructor is executed, evaluate it also in the constructor with new data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question