Java Reference
In-Depth Information
Let's create a class
ClassAccessTest
in the
com.jdojo.common
package. Note that the package for the
ClassAccessTest
class is different from the package for the
Human
class. The code for the
ClassAccessTest
class is
// ClassAccessTest.java
package com.jdojo.common;
public class ClassAccessTest {
public static void main(String[] args) {
Human jack;
}
}
The code for the
ClassAccessTest
class is very simple. It does only one thing—declares a reference variable of
Human
type in its
main()
method. Compile the
ClassAccessTest
class. Oops! You got a compilation time error.
"ClassAccessTest.java": cannot find symbol; symbol : class Human, location: class com.jdojo.common.
ClassAccessTest at line 6, column 5
If you read the error carefully, the compiler is complaining about the type
Human
in the following variable
declaration:
Human jack;
The compiler is stating that it could not find the definition of the term
Human
. What is wrong in the
ClassAccessTest
class with the
jack
variable declaration? When you refer to a class by its simple name, the compiler
looks for that class declaration in the same package where the referring class is. In your case, the referring class
ClassAccessTest
is in the
com.jdojo.common
package and it uses the simple name,
Human
, to refer to the
Human
class.
Therefore, the compiler looks for the
Human
class in the
com.jdojo.common
package. The compiler is looking for a
com.
jdojo.common.Human
class, which you do not have. This is the reason why you received the error.
By using the simple name
Human
in
ClassAccessTest
, you meant to refer to the
Human
class in the
com.jdojo.cls
package, not in the
com.jdojo.common
package. If you had the
Human
class in the
com.jdojo.common
package, your code
for
ClassAccessTest
would have compiled. Let's assume that you do not have a
com.jdojo.common.Human
class and
you want to fix the compilation time error. You can fix it by using the fully qualified name of the
Human
class, like so:
// ClassAccessTest.java
package com.jdojo.common;
public class ClassAccessTest {
public static void main(String[] args) {
com.jdojo.cls.Human jack;
}
}
Now compile the
ClassAccessTest
class. Oops! You got a compilation time error again. However, this time,
the error is different.
"ClassAccessTest.java": com.jdojo.cls.Human is not public in com.jdojo.cls; cannot be accessed from
outside package at line 6, column 24