Is there a way to pass a package private class to static method

1.1k views Asked by At

I'm wondering if there is a way to call static method from another package which take a package private class as a parameter? is that the only way to move MessagePackagePrivate class to another .java file and make it public ? it gives this error if i don't do that : "The type MessagePackagePrivate is not visible" which is normal.

So if it is the case that means, even if your class expose a static method to be used publicly ,that class cannot be used if it is not being called in the same package?

here is the code snippet:

MainClass.java

package packageA;

import packageB.*;

public class MainClass {
    public static void main(String[] args) {
        ClassB.printString(new MessagePackagePrivate("Package problem"), 12);
    }
}

ClassB.java

package packageB;

public class ClassB {

    public static void printString( MessagePackagePrivate message , int numbers) {
        System.out.println(message.getMessage() + " numbers: " + numbers );
        // other logics will be implemented here ...
    }
}

    class MessagePackagePrivate {
        private String text;

        MessagePackagePrivate(String text) {
            this.text = text;
        }

        public String getMessage() {
            return this.text;
        }
    }
2

There are 2 answers

2
biziclop On

This is what interfaces are for.

You have a public interface (well, all interfaces are public) that defines all the methods that need to be publicly accessible and a package private implementation. And the method you pass the object to only needs to know about the interface.

In your case you'll have something like this:

public interface Message {
  public String getMessage();
}

And then

class MessagePackagePrivate implements Message {
   ...
}

Finally:

public static void printString( Message message , int numbers) {
   ...
}
0
Fabian Barney On

You can implement an interface (say Printable) and use that interface as parameter type in your static method.