view raw
Yumi Koizumi Yumi Koizumi - 11 months ago 24
Java Question

How to cleanly interact with nested class in java?

How can one store & access attributes in the following way in Java?

InnerTest it = new InnerTest(); = "123";
it.user.userID = "456";

The following code does not do what is desired, but it offers a backdrop for the question:

public class InnerTest {
public String id;
static class user {
static String userName;
static String userID;

In case my approach is way off, the exercise is to store a JSON architecture in a class, but access it simply as given above. I am creating a class for Tweets, and one inner group of attributes is under "user":

"in_reply_to_user_id" : null,
"in_reply_to_user_id_str" : null,
"in_reply_to_screen_name" : null,
"user" : {
"id" : 19792676,
"id_str" : "19792676",
"name" : "(((Payne¯\\_(ツ)_/¯)))",

I am looking for a way to elegantly represent in my class' use those inner variables, as in:

foo.user.id_str ...

Is a type of nested/anonymous class correct? It doesn't look like it is-even with static modifiers...


Nested class is a good choice in this situation. However, you misunderstood the purpose of static in a static class - this is a syntax for creating classes that can be created independently of the instance of their outer class. It is not a class that must have only static fields and methods.

Therefore, your declaration should be fixed to make userName and userId fields non-static:

public class InnerTest {
    public String id;
    public UserType user = new UserType();
    static class UserType {
        String userName;
        String userID;