Syed Mudabbir
Syed Mudabbir

Reputation: 287

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() {
    }
}

Upvotes: 4

Views: 5164

Answers (2)

William Morrison
William Morrison

Reputation: 11006

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

Upvotes: 6

abma
abma

Reputation: 81

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

Upvotes: 0

Related Questions