I am using Eclipse.
2 folders: src/test and src/main
Both have a package with same name: Academy
.
The Academy
package in src/test has in it a class name: Base.java
The Academy
package in src/main has in it a class name: HomePage.java
In the HomePage.java class, extends Base
is not detecting base class in it.
This is the code inside HomePage.java
package Academy;
import Academy.Base;
public class HomePage extends Base{
}
There is a red line on Academy.Base
and on Base
. It tells to make Base
class, but it is already there. I tried to save the file. I tried to make new project too. Please Help. Thank you.
Here is the reference image:
CodePudding user response:
You are using Maven as the build system for your Eclipse project.
Maven does not allow a class in your main tree to depend on a class in the test tree. It prevents this by telling the Java compiler and runtime that classes and resources in the test tree are not in the build time and runtime classpaths for the main code. That is why you are getting the compilation error.
Solution:
Move the Base.java
class into "src/main/java/Academy" directory.
You commented:
It's just 2 packages with same name, inside 2 different folders. whether it's test or not, it should still inherit with extends.
Sorry ... but you are wrong. It does matter which tree you put the classes in. This is a Maven, and Maven is "opinionated" about these things. (For good reason, IMO. But either way, Maven opinion takes precedence ... if you choose to use Maven)
There are a couple of other problems:
A package name should start with a lowercase letter. Read this for example.
Solution: Rename
Academy
toacademy
1.Non-code resources should not be in a "java" directory. Non-code resources in a "java" source directory won't be on the runtime classpath ... and won't be included in (regular) JAR files.
Solution: Create a "resources" directory and put it there.
The
import Academy.Base;
is redundant. It is not necessary to import a class in the same package.
1 - Alternate solution: don't ask other people to work on your code, or help you with it. If other people don't ever need to read your code, it only matters to you what your code looks like. The compiler doesn't care. Only humans do.
CodePudding user response:
The import
was irrelevant.
Your src/main/java/, src/main/resources/ are packed for your main product, probably something like E2EProject1.jar.
Your src/test/java/, src/test/resources/ are packed in your unit tests, probably something like E2EProject1-test.jar. These test classes are kept outside your main product, but have the main product on the class path as dependency.
So it should be something like:
- src/main/java/Base.java
- src/test/resources/data.properties (or src/main/resources/)
That the packages are named identical is for being able to test (implicitly import) non-public, package private classes of src/main/java in unit test classes in src/test/java.