When I attempt to compile a Java source that is defined in a package, that imports another Java source that is not in a package, I receive a syntax error

By: Christopher Moeller

Abstract: Explanation and workaround for bug fixed in the JDK.

Question:

When I attempt to compile a Java source file that is defined in a package, that imports another Java source file that is not in a package, I receive the following error message:

"Bar.java": Error #: 200 : '.' expected at line 3, column 10

Here are the two source files:

//----------------------------------------------

public class Foo {

public Foo() { System.out.println("Foo"); }

}

//----------------------------------------------

 

//----------------------------------------------

package com.test;

import Foo;

public class Bar {

public Bar() { System.out.println("Bar"); }

public static void main(String[] args) {

Bar bar = new Bar();

Foo foo = new Foo();

}

}

//----------------------------------------------

I know this code used to compile. Why this this error now occuring?

 

Answer:

Bar.java fails to compile because the import statement is looking for the package that includes Foo. The import statement cannot find Foo, because Foo is not defined in any package.

A single-type-import declaration imports a single type by giving its fully qualified name, but it is still a requirement that the imported class be defined in a package:

import com.test.TypeName; // example

The TypeName must be the fully qualified name of a class or interface type; a compile-time error occurs if the named type does not exist. If the named type is not in the current package, then it must be accessible in an accessible package and declared public or a compile-time error occurs.

The reason that these source files would compile previously, is simply because of a bug with the previous version of the JDK. This issue is fixed with the release of JDK 1.4.1.

Nevertheless, if you wish to continue to compile legacy Java code designed in this way, do the following:

[JBuilder 8]

1. Choose: Project Properties | Build | Java | Compiler | Project javac

2. Choose: Project Properties | Paths | JDK | and select and pre-1.4.1 JDK (e.g. 1.3.1)

 

Here is a link to additional information regarding this issue:

http://bdn.borland.com/article/0,1410,29710,00.html


Server Response from: ETNASC04