D
D
Denis Pupchenko2017-08-22 21:26:33
Java
Denis Pupchenko, 2017-08-22 21:26:33

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.

  }
}

Output: null
Initially, the constructor without parameters will run, name will become null.
Why null should the local class constructor work and call the parent constructor with the parameter where the variable of the surrounding class will be set to the value "Name" ???

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Odissey Nemo, 2017-09-01
@odissey_nemo

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 question

Ask a Question

731 491 924 answers to any question