简体   繁体   中英

Why doesn't java allow to declare and initialize a class-level variable in two different steps

Can anyone explain me,

  1. Why doesn't java allow to declare and initialize a class-level variable in two different steps.
  2. Why can't I declare a public variable in public method.
public class Class10 {
    public String i=" ";
    public String j;
    j=" "; //Does-Not work

    public void method(String[] args){ 
        public String k=" "; // Does-not work  
        j=" ";
    }
}

1) It is possible with the right syntax (but discouraged) :

public class Class10 {
  public String i=" ";
  public String j;
  {j=" ";} //This is called an "Instance initialization block"
  //It would be better to do it in a constructor.

2) It does not make sense :

  • If you want it to be visible to others methods, it should be an attribute.
  • If you want it to be local to the methods, it should be a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM