Java Packages


Java Packages


Learning a Programming language and especially a robust OOP language such as Java is a process--or rather many processes.  This post covers an example of such a process.

I knew what namespaces were/are. 
I thought of a namespace as a dictionary, or glossary, or maybe a reference codebook.  I still think that works for me, but I found this definition in one of the links below:
  • A namespace is a group of related elements that each have a unique name or identifier.
Just as computer operating systems, domain names, and so many other structures need namespaces, so does Java.

I learned how to use packages

I just told my IDE (yes, more on command line preferences in other posts) to make a package, then when my classes and interfaces were inside that package they had access to each other.

I knew that Java comes with its own packages which provide ways to extend visibility among various classes/java files

The package keyword, if it appears, must be the first token of Java code (i.e., the first thing other than comments and space) in the Java file. This keyword defines the package of the class or interface or other...the java file.

Java uses packages instead of namespaces

Things came together.  Packages are used to define Java namespaces.  Two classes of the same name is a problem, unless they are marked unique by being in different packages.

As stated above, namespaces must ensure uniqueness (thus the dictionary or codebook) and prevent conflicts.  A class name NotMe can be used twice in Java as two different classes and still be unique because it appears in different packages.  How to use NotMe in the code?  Two ways:  1) Fully qualified would mean Packagename.NotMe......  2) or if I import Packagename then I can just use NotMe throughout the code.

Well, what if I try to import two packages with the same class names in them, or rather import two classes of the same name in different packages?  Java does not allow that.  See below message via Eclipse:








Solution:  Use fully qualified name throughout.

~~~

References, External

https://docstore.mik.ua/orelly/java-ent/jnut/ch02_11.htm

https://en.wikipedia.org/wiki/Java_package

https://en.wikipedia.org/wiki/Namespace

https://techterms.com/definition/namespace




Comments

Popular posts from this blog

Spring Boot, parsing the pom.xml

Coding Philosophy

Java: Reference vs. Object