如何从java中的不同类访问私有类的公共方法? [英] How can you access public methods from private class from a different class in java?

查看:204
本文介绍了如何从java中的不同类访问私有类的公共方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是有一个问题,有没有办法从一个来自不同类的私有类访问公共方法?例如,可以从不同的类访问print方法,因为该类是私有的?

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


推荐答案

是的。

您实际上并没有返回对私有类的直接引用,因为其他类不能使用它。相反,您扩展了一些公共类,并将您的私有类作为该公共类的实例返回。然后可以调用它继承的任何方法。

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

这篇关于如何从java中的不同类访问私有类的公共方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆