Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I have to import a class I just made to use it in my main class? (Java)

Tags:

java

import

class

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.

like image 796
naitreid Avatar asked May 27 '11 12:05

naitreid


People also ask

How do I import a class I made in Java?

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.

Do you need to import classes in Java?

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).

What happens when you import a class in Java?

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 .


2 Answers

It is because both are in same package(folder). They are automatically imported no need to write import statement for that.

like image 78
Harry Joy Avatar answered Sep 22 '22 15:09

Harry Joy


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.

like image 34
JB Nizet Avatar answered Sep 20 '22 15:09

JB Nizet