我如何访问包外的默认类的公共方法 [英] how do i access a public method of a default class outside the package

查看:106
本文介绍了我如何访问包外的默认类的公共方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有修饰符的类(默认),它有一个名为mymeth的公共方法。我知道当我在包内时我可以访问该方法。但是,当我在包外时,我想访问该方法。有没有人知道如何做到这一点。理论上我认为它应该是可能的,因为公共方法意味着世界的访问。这是我的类和方法的示例:

I have a class with no modifier(default), which has a public method called mymeth. I know I could access the method when I am within the package. However I would like to access the method when I am outside the package. does anyone has an Idea on how it could be done. theoretically I think it should be possible since public method means access by the world. here is the example of my class and method:

class myclass{

public void mymeth(int i,int b){

.....
  }

}


推荐答案

public interface SomeInterface{
   public void mymeth();
}

class MyClass implements SomeInterface{

   public void mymeth(){

   }
}

//is in the same package as MyClass
public MyClassFactory{
   public SomeInterface create(/*parameters*/){
       //create instance from parameters
       //For your case
       MyClass instanceOfAnyClassThatImplementsSomeInterface = new MyClass(/*pass the parameters*/); 
       return instanceOfAnyClassThatImplementsSomeInterface;
   }
}

其中一种方法已在答案中定义但是如果你想限制类的公共访问,那么你可以创建一个接口并通过它访问该方法。

One of the ways is already defined in answers but If you want to restrict the public access of the class then you can create an interface and access the method through it.

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

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