简体   繁体   中英

(Java) Accessing public variables in inner class?

How can I code a struct-like class that contains public variables, and then be able to access them from another class without using getters and setters?

I know how to do getter/setter but they just take a lot of typing space, so I was wondering if maybe using an inner class would eliminate that? From what I understand, static means I can have only one x variable, which I can't do, because I need an array.

public class publicClass {
    innerclass array_inner[];

    class innerclass {
        private int x;
        innerclass(int x){this.x = x;}
        ...
    }

    public publicClass {array_inner = new innerclass[5];}

    public access_x {
       array_inner[0].x; 
    }

}

Your code contains a bunch of mistakes and they have nothing to do with accessing inner class variables. Also, inner and nested are different notions, and as already mentioned in the answers you have wrong understanding of what is static in java. Anyway here is corrected code with no compilation errors:

public class PublicClass {
  Innerclass array_inner[];

  class Innerclass {
    private int x;

    Innerclass(int x) {
      this.x = x;
    }
  }

  public PublicClass() {
    array_inner = new Innerclass[5];
  }

  public void access_x() {
    System.out.println(array_inner[0].x);
  }

  public static void main(String[] args) {
    PublicClass publicClass = new PublicClass();
    publicClass.array_inner[0] = publicClass.new Innerclass(0);
    publicClass.access_x();
  }
}

Output:

0

如果要访问,必须将该变量设为静态

Here the InnClass can access the OutClass methods and attributes by its own methods as implimented. So glide through the provided code, it may help you : --

class OutClass {    //Outer Class

    String a = "AutoSpy", b = "Beef", c = "Crunch";

    class InnClass{ //Inner Class
        int i;
        public String accessA(){
            return a;   // Accessing Outer class variable (a) inside inner class
        }
    }

    public static class StaticInnClass{
        int i;
    }

    public String combineString(){
        return a + b + c + " : Combined";    
    }
}

public class MainClass{

    public static void main(String args[]) {

        OutClass.StaticInnClass staticClass = new OutClass.StaticInnClass();
        OutClass outer = new OutClass();
        OutClass.InnClass inner = outer.new InnClass();
        System.out.println(inner.accessA());
    }
}

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