Question

I know C++ at a decent level and I am trying to learn java. This will be a silly question but I cannot figure out how to import a .java file into another. I am at Eclipse IDE and in my project I have two files:

FileReader.java

Entry.java

I want to import the Entry.java in the other file but no matter what I do I get an error. Can you help me? Thx in advance.

FileReader.java :

import java.io.*;

     class FileReader {
            public static void main(String[] args) throws Exception {

                System.out.println("Hello, World");
                Entry a(10,"a title","a description");
                a.print();

            }
        }

Entry.java:

public class Entry{
    int ID;
    String title;
    String description;


    public Entry(int id, String t,String d){
        ID=id;
        title=t;
        description=d;

    }

    public void print(){
        System.out.println("ID:"+ID);
        System.out.println("Title:"+title);
        System.out.println("Description:"+description);
    }
}

At this state I get an error that Entry cannot be resolved as a variable. So I believe that it is related to the import.

Was it helpful?

Solution

Firstly

Entry a(10,"a title","a description");

should be

Entry a = new Entry (10,"a title","a description");

If Entry is in the same package then you will not need to import it.

If Entry is in a different package, say com.example then you will need to do

Either

import com.example.Entry;

or

import com.example.*;

The second import will import all classes in the com.example package - usually not such a good thing.

OTHER TIPS

You need new Entry

The new keyword creates the new object

Entry a = new Entry(10,"a title","a description") 
a.print();

An Entry object is created with the a reference with the above instantiation.

For the import part of your question, if two files are in the same package, no import is needed. If you Entry class was in a different package than your FileReader class, then you would need to import mypackage.Entry

Try

Entry a = new Entry(/*args*/);

And if you need to import the class, then use the absolute name (package+class) and put it after import above the class declaration

import com.example.you.Entry;

In Eclipse you can do Ctrl+Shift+O to resolve all imports.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top