简体   繁体   English

不能在java中使用另一个类的公共方法

[英]Cant use a public method from another class in java

I am trying to call a public constructor of a public class located in one package of my project from the main class, located in a class from another package different to the first one, but located in the same project.我试图从主类调用位于我的项目的一个包中的公共类的公共构造函数,该类位于与第一个不同的另一个包的类中,但位于同一个项目中。

I have understood that the public modifier grant you access to methods from any location inside or outside the package, so i just try to create and instance a new object of the public class first mentioned.我知道 public 修饰符允许您从包内部或外部的任何位置访问方法,所以我只是尝试创建和实例化首先提到的公共类的新对象。

FE: I try something like.... ClassName newObject = new ClassName(); FE:我尝试类似.... ClassName newObject = new ClassName(); from the main class从主类

Actually, in order to be able of using that (im using netbeans IDE) I need to import the class/method I want to call, even if they have the public modifier.实际上,为了能够使用它(我使用 netbeans IDE),我需要导入我想要调用的类/方法,即使它们具有 public 修饰符。

My question is... is there a way of using these methods without the need of importing them to the main class ?我的问题是......有没有办法使用这些方法而无需将它们导入主类?

I am new in this webpage, so sorry if there is anything wrong with the question.我是这个网页的新手,如果问题有任何问题,很抱歉。

You could use the fully qualified class Name instead.您可以改用完全限定的类名称。

a.b.c.MyClass myClass = new a.b.c.MyClass();

Also see Java: import statement vs fully qualified name?另请参阅Java:import 语句与完全限定名称?

Qualification and visibility have little to do with eachother.资质和知名度几乎没有关系。 Those are different concepts.这些是不同的概念。

Visibility (enforced by access modifiers like public , protected , private and package-private ) is about which class may access (ie call or use) it.可见性(由publicprotectedprivatepackage-private访问修饰符强制执行)是关于哪个类可以访问(即调用或使用)它。

Qualification is about the compiler asking you: "Okay, you are mentioning a class name, but there could be thousands around with that name. Which one do you mean?"限定是关于编译器问你:“好吧,你提到了一个类名,但是这个名字可能有数千个。你是指哪个?”

Java compiler restricts its search for classes inside the package only. Java 编译器只限制搜索包内的类。 In order to make use of any class belonging to a different package, you have to import it explicitly.为了使用属于不同包的任何类,您必须显式导入它。 You can read more about packages here .您可以在此处阅读有关软件包的更多信息。

Access specifiers are more from restricting the methods from being accessible by outside world.访问说明符更多地用于限制方法被外部世界访问。 These access specifiers enforce further restrictions on top of what is enforced by packages.这些访问说明符在包强制执行的内容之上强制执行进一步的限制。 You can refer to this link for access specifiers.您可以参考此链接以获取访问说明符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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