Answer the question
In order to leave comments, you need to log in
Why, when accessing a variable of the surrounding class from a local class, after its explicit initialization, it shows it as null?
Why, when accessing a variable of the surrounding class from a local class, after its initialization by calling the constructor of the surrounding class from the constructor of the local class, does it show its default value?
interface ITest{
void getName();
}
class Test{
private String name;
Test(String name) {
this.name=name;
}
Test() { }
public ITest setName(String name1){
class Test1 extends Test implements ITest{
Test1 (String name1) {
super(name1);
}
@Override
public void getName(){
System.out.println(name);
}
}
return new Test1(name1);
}
}
public class Main {
public static void main(String[] args) {
Test test= new Test();// Запустится конструктор без параметров, name станет null.
ITest itest= test.setName("Имя"); // Здесь конструктор с параметром, установит переменной name значение "имя";
itest.getName(); // она все еще null.
}
}
Answer the question
In order to leave comments, you need to log in
Everything is logical, albeit confusing. A variable of one class (Test) is set, and another class is read (Test1).
If you call itest.setName("Name2") in main, then itest.getName() will print "Name2" :o)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question