I am currently learning Java using the Deitel's book Java How to Program 8th edition (early objects version).
I am on the chapter on creating classes and methods.
However, I got really confused by the example provided there because it consists of two separate .java files and when one of them uses a method from the other one, it did not import the class. It just created an object of that class from the other .java file without importing it first.
How does that work? Why don't I need to import it?
Here is the code from the book (I removed most comments, to save typing space/time...): .java class:
//GradeBook.java public class GradeBook { public void displayMessage() { System.out.printf( "Welcome to the grade book!" ); } }
The main .java file:
//GradeBookTest.java public class GradeBookTest { public static void main( String[] args) { GradeBook myGradeBook = new GradeBook(); myGradeBook.displayMessage(); } }
I thought I had to write
import GradeBook.java;
or something like that. How does the compiler know where GradeBook class and its methods are found and how does it know if it exists at all if we dont import that class?
I did lots of Googling but found no answer. I am new to programming so please tolerate my newbie question.
Thank you in advance.
Otherwise, it is very easy. In Eclipse or NetBeans just write the class you want to use and press on Ctrl + Space . The IDE will automatically import the class.
In Java, you do not need to add import statements for classes that exist within the same package (they are actually automatically “imported” by the compiler).
In Java, import is simply used by the compiler to let you name your classes by their unqualified name, let's say String instead of java. lang. String .
It is because both are in same package(folder). They are automatically imported no need to write import statement for that.
You don't have to import classes that are in the same package as the current class.
Also, note that GradeBook.java is the name of the file. The (simple) name of the class is GradeBook. Every class should be in a package. If it is in the package com.foo.bar, the class name is com.foo.bar.GradeBook, and this is the name you must use when importing this class.
Read http://download.oracle.com/javase/tutorial/java/package/packages.html to learn more about packages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With