How can you access public methods from a private class from another class in java?

I have a question, is there a way to access public methods from a class that is private from another class? For example, can a printing method be available from another class, since the class is private?

private class TestClass { public void print() { } } 
+4
source share
2 answers

Yes there is.

In fact, you are not returning a direct link to your private class, as other classes cannot use it. Instead, you extend some public class and return your private class as an instance of this public class. Then you can call any methods that he inherited.

 public interface Printable { void print(); } public class Test { public Printable getPrintable() { return new PrintTest(); } private class PrintTest implements Printable { public void print() { } } } Test test = new Test(); test.getPrintable().print(); 
+4
source

You can do this by extending this class with an open class. Or you can always use reflection!

0
source

Source: https://habr.com/ru/post/1494846/


All Articles