通过使用完整类名或导入特定的类来准确定位所需的类
示例代码: 在包com.example.a中定义了一个名为Test的类:
package com.example.a; public class Test { // code implementation }
在包com.example.b中也定义了一个名为Test的类:
package com.example.b; public class Test { // code implementation }
当我们在另一个类中需要使用这两个类的其中一个时,就需要进行准确定位,防止出现同名类的冲突。以下两种方法均可解决这个问题:
com.example.a.Test test1 = new com.example.a.Test(); com.example.b.Test test2 = new com.example.b.Test();
这样就可以区分开来两个同名的类。
import com.example.a.Test;
public class MyClass { Test test = new Test(); }
通过使用import语句导入所需的类,我们就可以在代码中只使用类名而不需要写出完整类名了。如果需要同时使用两个同名类,那么可以使用static import语句来导入具体的方法或字段,以避免命名冲突:
import static com.example.a.Test.method1; import static com.example.b.Test.method1;
public class MyClass { public void foo() { method1(); // 调用不同包中同名的method1方法 } }