简体   繁体   中英

why class define in other package can not implement interface or extends class define in default package in java

Below interface define in default package

public interface Foo{  
}  

package com.code  
public class  MyClass implements Foo{  
}

Above code will give following compilation error:
Foo can not be resolved to type
why???

That is why it is recommended that you put all your code into packages.

When you reference a class or interface without using a package name then the assumption is that the class is in the same package as the code in which it is referenced. So the compiler is seeing this:

  package com.code  
  public class  MyClass implements com.code.Foo{  
   }

Since there is no way to reference the default package in code then do not use it.

如果您希望您的类实现一个接口,那么您应该将它们都放在同一个包中或者在创建类之前导入包含该接口的包或者在声明中使用该接口的整个路径。

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