user1866527
user1866527

Reputation: 31

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???

Upvotes: 3

Views: 3708

Answers (2)

Kash
Kash

Reputation: 43

If you want your class to implement an interface,then you should either have both of them in the same package Or import the package which contains the interface before creating your class Or use the whole path of the interface in the declaration.

Upvotes: 0

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

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.

Upvotes: 1

Related Questions