Today I want to share some of my thoughts about java packages. Most of the time I don't have to dig deep into java's internals etc. Most of the time I use C# and Unity 3D, so java is used only when it comes to write some plugin or do some tests. Copy-paste from Stack Overflow is usually good enough. But not today. Today is the day to finally clarify some things.
I decided to present it in a form of Q&A, so here you have questions and answers:
What is java package?
The very first thing that comes to my mind, when I hear package, is that package is some kind of file. Something like Linux package etc. So, I was thinking that java packages are also some kind of files. Maybe *.jar files ?
No. It's not the case. The package in java is acctually a namespace. Every *.java file must start with first line like this: package com.alientechlab.somepackage; - that means, that all classes in this file belong to package/namespace com.alientechlab.somepackage. You can have many *.java files that contains that first line. That means, that all classes in all those *.java files belong to the same package/namespace.
Isn't a *.jar file a package file?
No. At least not in a sens of java. It does contains *.class files but those classes inside those *.class files can belong to different packages/namespaces. It's just a container for *.class files - acctually it's yet another compression file format like *.zip or *.rar. Actually it is modified ZIP file format. You can even open this file using winrar. You can think about *.jar files like a package, but only in the same sens as Linux package. Just file containing other compressed files.
What is *.class file ?
It's *.java file after compilation. To compile *.java file manually, type in terminal:
1 2 3 |
javac SomeFile.java |
If javac is unrecognized command then add path (usually something like: "C:\Program Files\Java\jdk1.8.0_121\bin") to PATH environment variable.
So, what is *.jar file?
It's acctually a *.zip file. Zip file that contains *.class files. To create *.jar file type:
1 2 3 4 |
jar cf MyJarFile.jar MyJavaFile1.class MyJavaFile2.class # To create jar from files directly or jar cf MyJarFile.jar FolderName # to create jar from folder containing *.class files |