1
votes

I am creating a package com.XXXX Inside that I am declaring many classes in a java file (default - not public)

let is be like:

class A{}
class B{}
class C{}

I am importing com.XXXX in another file

I am unable to use these classes that are inside the package, as they are not public.

So I am pushing to a state of creating individual files for each classes.

Every class is just a small structure, where it doesn't have any extra function. So I thought of keeping them in single file. So I can't declare classes as public

Is there any way to use all classes without splitting them into separate files?

3

3 Answers

1
votes

If (somehow) it makes sense to group these classes together, then you could put them inside a wrapper class as static inner classes, for example:

package com.somewhere;

public class Utils {
    public static class DateUtils {
        public static Date today() {
            return new Date();
        }
    }

    public static class FilenameUtils {
        public static String stripExtension(String path) {
            return path.substring(0, path.lastIndexOf("."));
        }
    }
}

Then, you will be able to import these elsewhere:

package com.elsewhere;

import com.somewhere.Utils;

public class Task {
    Date today = Utils.DateUtils.today();
}
1
votes

This is because the default java access modifier is package private. When you create the classes without an access modifier they become accessible only within the package.

If you don't want to expose it outside the jar then rename your package to be com.internal.XXXX. When you put the internal keyword that package wont be available outside the jar even thought your classes inside the package would be public.

1
votes

If you want to have more than one class in the same file, you can use Nested Classes.

Please, take a look at: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Example:

class OuterClass {
    ...
    class NestedClass {
        ...
    }
}

You can then refeer to OuterClass.NestedClass from another package