Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import my own class?

I have this java class :

package myClass;
public class myClass 
{
    private int herAge ;
    public void setHerAge (int herAge)
    {
        this.herAge = herAge ; 
    }
}

and I want to import this class after compile it in another source file called Test.java exists in the same directory , and here what Test.java contains :

import myClass ;
public class Test
{
    public static void main (String []args)
    {
    myClass Rudaina = new myClass();
    Rudaina.setHerAge(30);
    }
}

when I compile Test.java I see this in my console :

Test.java:1: error '.' expected
import myClass ;
              ^
Test.java:1: error '.' expected
import myClass ;
                ^
like image 451
mahmoud nezar sarhan Avatar asked Feb 21 '15 20:02

mahmoud nezar sarhan


2 Answers

Your class myClass is also in package called myClass, which can be a cause of confusion.

Try:

import myClass.myClass;

This is called the fully qualified name of the class.

A package is meant to group classes which are conceptually related. Having a package named after a single class is not very useful.

You could name your package after the name of your project. For instance, you could name it

package assignment1;

And then import your class like this:

import assignment1.myClass;
like image 91
iFytil Avatar answered Sep 27 '22 19:09

iFytil


While what everyone wrote is true, since the two files are in the same directory, no import should be necessary.

FYI, it is customary to capitalize the names of classes.

like image 34
Ellen Spertus Avatar answered Sep 27 '22 19:09

Ellen Spertus