Search code examples
javajava-package

Import package and how to use all classes in a java file


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?


Solution

  • 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();
    }