简体   繁体   中英

Import statement of ClassA within ClassA ?? why did designers allow this.?

I have below doubt on import statement in java.

    package com.punith.test;
    import **com.punith.test.ClassA**;

    public class ClassA {

    }

So as in above code i am allowed to import the same class which i am defining ClassA. So why did designers allowed to do this, instead of compilation error corrected to be as a warning.

Regards Punith

It's just a special case of an unused import, which quite rightly don't throw compile errors. There is no performance hit from unused imports since this is a compile-time indicator that you intend to use a class at runtime.

There are countless ways to create pointless code; to have each one throw a compile time error would make the compiler considerably more complex. Best to rely on an element of common sense from the developer and when common sense fails (all too often), optimise out the dodgy code - which happens in this case.

自我导入类不会产生编译错误,但是将其作为自我导入是没有意义的。

There are some thoughts about your question.

First of all, lets consider, why compiler deprecates some code constructions? In which case? Obviously, any compiler error is the signal about incomprehensible part of code, which can not be correctly translated into low-level instructions, and so it can not be interpreted by JVM. All other cases, which are senseless or absurd, but which could be implemented - aren't deprecated. For example, you can also do a lot of meaningless things in Java:

public void nop() {
    int i;
}

or

for (int x = 0; x < 0; x++);

or

int i = 1;
i = i;

Secondly thought about import statement is not exactly about your question, but it is close by it. There is also import static statement. This is a very case where static import of same class, which is described in this file is sensible thing. For example it is helpful in such situation:

package xxx;
import static xxx.TestEnum.Test.*;
public class TestEnum {
    enum Test {
        TEST1,
        TEST2
    }
    public boolean isTest2(Test test) {
        return test == TEST2;
    }
}

In this code without import static xxx.TestEnum.Test.* we can not use such construction as test == TEST2; . Without such import it will be compile error and we have to change it to return test == Test.TEST2; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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