How to create a package in java - java

How can one create a package in Java:
In a book i read its :
package package_name
public class whatever{}
.
.
.
But shouldn't this be enclosed in parenthesis such as :
package package_name
{
public class whatever{}
.
.
.
}
Just a minor confusion. Can anyone give me an example of the correct syntax?

The syntax for creating package
package package_name;
public class Whatever {
}
You can find more useful info Here.

When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.
Reference
Example :
package illustration; <------------
import java.awt.*;
public class Drawing {
. . .
}

Package is created as follows
package package_Name;
This package name has to be the first statement in the file.Once you declare package name start defining methods or classes or interfaces in it.
If this package you have to use in your any java file then write
import package_Name;
so that all the methods defined in the package will be accessible in java file.

No parenthesies. Package is nothing else then just a folder or set of folders. For example, if you create package named: utils, new folder will be created in your source folder. If you create package named org.utils, two folders will be created in your source folder. org and utils which will be inside of org folder. Also, every next package which starts with org. (for example org.ui) will be just a new folder created in org folder. So your folder hierarchy will look like this:
org--
|
utils
|
ui

Related

Java Package Hierarchy: Middle Level Cannot Find Lower Level Despite Import Statement

I have defined a data structure that uses another, lower-level data structure, which I also defined. For tidiness, I want each data structure to have its own directory and package name. Suppose the higher-level data structure's package is called packageA and the lower-level packageB. Then, I want to use the data structure defined in packageA in a program-say, Program. So I have a directory structure like this:
Program
|- Program.java
|- packageA
|- ClassA.java
|- packageB
|- ClassB.java
ClassB.java has at the top
package packageB;
ClassA.java has at the top
package packageA;
import packageB.ClassB;
And then Program.java has
import packageA;
and refers to ClassA in its code.
When I try to compile at the top level with javac *.java, I get the error that package packageB does not exist.
What am I doing wrong, and how can I accomplish this simple goal? Thank you.
Your import statement in ClassA.java is wrong. The import statement for a type has to be its canonical name. Here's what JLS 7.5.1 says:
7.5.1. Single-Type-Import Declarations
A single-type-import declaration imports a single type by giving its canonical name, making it available under a simple name in the module, class, and interface declarations of the compilation unit in which the single-type-import declaration appears.
The TypeName must be the canonical name of a class type, interface type, enum type, or annotation type (ยง6.7).
And the relevant definition for canonical name in section 6.7 is
The fully qualified name of a named package that is a subpackage of another named package consists of the fully qualified name of the containing package, followed by ".", followed by the simple (member) name of the subpackage.
This does not make it possible to use relative package names to import. Your import statement must be
import packageA.packageB.ClassB;
And the package declaration in ClassB.java itself must be
package packageA.packageB;
I'm assuming that Program is not a package;

Why it complains when I import a self-defined package like below?

I have build two classes named PackageTest.java (in the desktop dir) and Employee.java (in the desktop/com/wenhu/corejava dir).
In the Employee.java file, I wrote in the first line:
package com.wenhu.corejava;
Then in the PackageTest.java file, I wrote in the first line:
import com.wenhu.corejava.*;
However, the compiler complains:
PackageTest.java:8: error: cannot access Employee
Employee harry = new Employee("Harry", 50000, 1989, 10, 1);
^
bad class file: .\Employee.class
class file contains wrong class: com.wenhu.corejava.Employee
Please remove or make sure it appears in the correct subdirectory of the classpath.
1 error
Interestingly, if I wrote:
import com.wenhu.corejava.Employee;
The compiler is OK!
Could anyone tell me why this is happened? I though the wildcard * could represent the Employee Class...
Thanks a lot!
Simple:
bad class file: .\Employee.class
class file contains wrong class: com.wenhu.corejava.Employee
Your setup is somehow messed up. It seems that you have a class file for Employee in your current directory.
The package name within the class file must match the file system location!
package com.wenhu.corejava;
This statement in the Employee class means that your class file Employee.java must be located in the directory com/wenhu/corejava/. But in your case it is in the directory which your java compiler as root of all sources understand, i.e. the default package.
To resolve your problem, either remove the package declaration mentioned above, which is not recommended, or create the corresponding directory and move the source file Employee.java to it.

Importing and Packages

I'm not quite sure what I'm doing wrong, here. I have two files in a directory, let's call them FileA.java and FileB.java.
FileA.java has a definition along the lines of:
package com.domain.package;
import stuff;
import package.FileB;
public class FileA extends Blah implements Listener {
/* global vars */
/* methods */
}
FileB.java is my data object class, which I'd like to reference from FileA.java thusly:
Map<Object, FileB> varname;
to be used along the lines of:
varname = new HashMap<Object, FileB>();
FileB.java, on the other hand, is defined as such:
package com.domain.package;
import stuff;
public class FileB {
/* global vars */
public FileB() {
/* stuff */
}
}
Why am I getting:
FileA.java:20: package package does not exist
import package.FileB;
? Rather, how do I make it work?
Because both files are in the same package (com.domain.package), you should not need to import FileB at all. You should be able to reference it directly.
Additionally, please ensure that both FileA and FileB are placed in their package folder: com/domain/package.
The package of FileB is com.domain.package. You are trying to use package.FileB instead.
package is a reserved word, don't use it as part of a package name. If you try to add a package with "package" as part of it in Eclipse, you will get an error message:
Invalid package name. 'package' is not a valid Java identifier
Rename the package, then remove the import statement. You don't need to import a file that's in the same package as the one it's referenced in.
#rgettman has the correct solution. Compiling both files using javac FileA.java FileB.javasolves this issue. You can also use his suggestion: javac *.java

The package collides with a type [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
eclipse 3.4 (ganymede) package collision with type
I'm new in java, but i tried to write a script for a game Lineage2.
heres a code:
package ZergZ.ZTeleport;
import javolution.util.FastMap;
import com.l2jserver.Config;
import com.l2jserver.gameserver.handler.IVoicedCommandHandler;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
import com.l2jserver.gameserver.model.Location;
import com.l2jserver.gameserver.handler.VoicedCommandHandler;
public class ZTeleport implements IVoicedCommandHandler
{
private static final String[] VOICED_COMMANDS =
{
"teleport"
};
#Override
public boolean useVoicedCommand(String command, L2PcInstance activeChar, String params)
{
if (activeChar == null)
return false;
if (params.equalsIgnoreCase("aden"))
{
activeChar.teleToLocation(147736,-56243,-2781);
}
if (params.equalsIgnoreCase("gracia"))
{
activeChar.teleToLocation(-186742,244167,2675);
}
if (params.equalsIgnoreCase("pvp1"))
{
activeChar.teleToLocation(147736,-56243,-2781);
}
if (params.equalsIgnoreCase("pvp2"))
{
activeChar.teleToLocation(179337,221937,4475);
}
}
#Override
public String[] getVoicedCommandList()
{
return VOICED_COMMANDS;
}
}
when server starts java says:
1. ERROR in \ZTeleport.java (at line 17)
package ZergZ.ZTeleport;
^^^^^^^^^^^^^^^^^^^^
The package ZergZ.ZTeleport collides with a type
the script is situated in ZergZ/ZTeleport.java
I'll give you another script which works fine:
package custom.HeroCirclet;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.quest.Quest;
import com.l2jserver.gameserver.model.quest.QuestState;
public class HeroCirclet extends Quest
{
______
}
Thanks.
You say "the script is situated in ZergZ/ZTeleport.java". This implies that the class ZTeleport belongs to the package ZergZ. But you have declared it as belonging to a different package, ZergZ.ZTeleport.
In your second example, I would bet that the source file is located in custom/HeroCirclet/HeroCirclet.java, which matches its package declaration, and does not create a naming conflict.
You either need to move the source file (people normally don't call java source files "scripts", btw) into a directory that matches its declared package, or change the package declaration to match its location.
It's because you have a class named ZTeleport in the ZergZ package and a package named ZergZ.ZTeleport.
The package name is basically the project directory where the Java file is situated.
That means if ZTeleport.java is in ZergZ directory, then the package name is
package ZergZ;
You don't specify the class name on package declaration and directory are separated with a . and not directory folder token.
The collision here is between your package name and your class name, which are the same. If you stick to the usual naming conventions (naming your packages with a starting lower case and your classes with a starting upper case), you should avoid such situations.
You should follow Java naming conventions. Change your package into:
package zergZ.zTeleport; // all name is begin with lower
// no change, but for clearer : all class name should begin with higher character
public class ZTeleport implements IVoicedCommandHandler
{
}
After that, for sure, you should refresh or/and rebuild your project to see it works.
Hope this help :)
If you see the error it says...
package ZergZ.ZTeleport;
^^^^^^^^^^^^^^^^^^^^
The package ZergZ.ZTeleport collides with a type
So basically you have created a conflict between the way you have named your class and the package. If you stick to java conventions you could name them as:
// Notice the first character of package name is small character
package zergZ.zTeleport;
// Class Name's first character is capital.
public class ZTeleport implements IVoicedCommandHandler{
..
}

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

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.
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.
The classes located in the same package do not have to be imported, as they are visible to each other. You simply import a class that is in another package:
import java.util.ArrayList;
Note that you are not importing the file, but the class.
It's all about packages. You are trying to use a class from the default package which does not need explicit import of the java file, ie GradeBook inside GradeBookTest
Here is where you can start with learning about packages :
Java Package Tutorial
and :
Creating and Using Packages
Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them.
From: Include one java file in another java file
Imports are for importing classes that are in a different package. Since you didn't declare a package for either they are both put in the default package. The compiler can find it because the class lives in the same directory.
You don't have to import classes which are in the same package.
Well, classes in the same package are automatically imported.
They're in the same package. This tutorial will do more justice than I will.

Categories

Resources