Answer the question
In order to leave comments, you need to log in
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();
}
}
Answer the question
In order to leave comments, you need to log in
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;
}
}
String.format(format,name,secondName,age)
, the fields will contain null
.
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 questionAsk a Question
731 491 924 answers to any question