4

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() {
    }
}
3
  • 2
    why don't you try it yourself is not difficult :) Commented Aug 1, 2013 at 22:35
  • The print method can be called on any TestClass object. The trouble comes in attaining such an Object. Commented Aug 1, 2013 at 22:35
  • But when I try it says method undefined for the class Commented Aug 1, 2013 at 22:51

2 Answers 2

6

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Oh So by implementing an interface we can create a link which allows us to access the print method from a private class? How about extending the private class and accessing it?
Yeah you could do that too, as the child class of the private class would also inherit from the super class of the private class. Hopefully that didn't confuse you as much as it did me haha.
Haha No you were really clear with an example and it helped me grasp it quicker. Thanks for your help.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.