Search code examples
javastaticnested

Accessing multiple nested static objects


I want to create a set of classes that allows me to write records

What I want to achieve is this

Record.write.field1();
Record.write.field2();

My understanding is that I can create multiple static nested objects but I'm struggling with it

I created the following

public abstract class Record{
public Write write;
}
public abstract class Write{
public static void field1();
}

The approach above hasn't helped me achieve that.

The questions I have is

Can I write a set of classes in a way so I can achieve the following pattern

Record.write.field1();
Record.write.field2();

This is so that I can scale it up when needing to add additional field

If I can, is this a good approach?

If I can't, what's the best approach? Thank you

UPDATE: I can do Record.write but can't do Record.write.field15();

public class Record {
    public static Write write;
}

public class Write {
    public static void field15(){
        System.out.println("Hello");
    }
}

Solution

  • This allows you to write the code the way you want:

    class Record {
        public static Write write = new Write();
    }
    
    class Write {
        public void field15(){
            System.out.println("Hello");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Record.write.field15(); // prints "Hello"
        }
    }
    

    Note that static methods are invoked on the class name, and instance methods are invoked on a specific instance value.