简体   繁体   中英

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

I just have a question, is there any way to access public methods from a class which is private from a different class? For Example the print method can be accessed from a different class since the class is private?

private class TestClass {
    public void print() {
    }
}

Yes there is.

You don't actually return an direct reference to your private class, since other classes can't use it. Instead, you extend some public class, and return your private class as an instance of that public class. Then any methods it inherited can be called.

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

You can do that by extending that class with a public class. Or you can always use reflection!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM