简体   繁体   English

当我显式使用另一个类中的一个类的公共函数时,为什么Java没有给我编译错误

[英]Why java doesn't give me compile error when I use public functions of one class in another class explicitly

I have two classes class1, and class1Test, in two different files, and two different folders. 我在两个不同的文件和两个不同的文件夹中有两个类class1和class1Test。 The first one is in folder src, and the second one in folder test (same project). 第一个在文件夹src中,第二个在文件夹测试中(同一项目)。 Now imagine I have this code in my class1Test and function1ofClass1 is public: 现在想象一下我的class1Test中有以下代码,并且function1ofClass1是公共的:

class1 c1 = new class1();
    int a = function1ofClass1();
    int b = c1.function1ofClass1();

Obviously the first call of function1ofClass1 is not correct, but in this situation, why java (I am using eclipse) doesn't give me a compile error? 显然,第一次调用function1ofClass1是不正确的,但是在这种情况下,为什么java(我正在使用eclipse)没有给我编译错误? I know that C# would. 我知道C#会。 Am I doing something wrong with my filing organization or this is the way java works? 我的归档组织有问题吗,或者这是java的工作方式吗?

看来您的测试类扩展了包含该函数的类,这就是为什么编译器不给您编译错误的原因。

The first one is in folder src, and the second one in folder test 第一个在文件夹src中,第二个在文件夹test中

And you are using an IDE which has set this up for you. 而且您正在使用为您进行设置的IDE。 It has added src/java and test/java to your classpath: as such, classes class1 (in, say, src/java/foo/bar ) and class1Test (in test/java/foo/bar ) are in the same namespace. 它将src/javatest/java到您的类路径中:这样,类class1 (例如src/java/foo/bar )和class1Test (在test/java/foo/bar )位于同一名称空间中。

It is therefore normal. 因此,这是正常的。

Is function1ofClass1 declared as static ? 是否将function1ofClass1声明为static In that case both calls are perfectly valid, provided the function has been imported (which your IDE may have done for you). 在这种情况下,只要函数已导入(IDE可能已为您完成),这两个调用就完全有效。

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

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