javaclassinner-classescustom-type

Java - Custom type nested in class


I am once again asking for technical support.

I need to define a custom type inside a class, I've done it like this:

public class MainClass {
    private class CustomType {
        public byte[] varA;
        public int varB;

        public CustomType() {
            varA = new byte[3];   
            varB = 13;
        }
    }

    private CustomType[] myArray;


    public MainClass() {
        myArray = new CustomType[1024]
        System.out.println(this.CustomType[0].varB);
    }
}

When I run it throws a NullPointerException at System.out.println(this.CustomType[0].varB);

I've tested if myArray gets properly initialized with 1024 elements and it does, however I can't seem to access them.

I just moved from C++ to Java so I'm still getting used to it, am I missing something blatant?.


Solution

  • Two things,

    So

    public class MainClass {
        private static class CustomType {
            public byte[] varA;
            public int varB;
    
            public CustomType() {
                varA = new byte[3];   
                varB = 13;
            }
        }
    
        private CustomType[] myArray;
    
    
        public MainClass() {
            myArray = new CustomType[1024];
            for (int i = 0; i < myArray.length; ++i) {
                this.CustomType[i] = new CustomType();
            }
            // Or
            Arrays.setAll(myArray, CustomType::new);
            System.out.println(this.CustomType[0].varB);
        }
    }
    

    Not making it static stores a MainClass.this in every CustomType instance which is unnecessary overhead.