0

I have created a project and Hello.java file without package name

public class Hello {
   public String sayHello(){
      return "Say Hello";
   }
}

I exported this project into hello.jar.

Now I have created another project and Main.java to call sayHello() method. I added hello.jar in classpath but the below code showing me an error 'Hello cannot be resolved to a type'

 public class Main {
   public static void main(String[] args){
     Hello h=new Hello(); // Error
  }
}
Sunil Singh Bora
  • 771
  • 9
  • 24

2 Answers2

3

It's not possible due to the fact that your Hello.java class needs to be inside a package stored in your JAR file to enable you to reference it. The structure of your JAR should at least be

hello.jar/packageName/Hello.java

after creating it like that it will be imported as

import packageName;

and you will be able to use classes from aformentioned package.

Dropout
  • 13,653
  • 10
  • 56
  • 109
0

No. It is not possible.
Try giving package name to Hello java file and then create again jar and then write import statement in Main class file

package com;
public class Hello {
   public String sayHello(){
      return "Say Hello";
   }
}

and in Main class add following line

import com.Hello;
public class Main {
   public static void main(String[] args){
     Hello h=new Hello(); 
  }
}
AmitG
  • 10,365
  • 5
  • 31
  • 52