Package in Java

Package in Java

Hello to my all Readers!....

Hope You All are having good Reading

Below I'm sharing my Todays learning regarding Technical Concept (Java Language). Have a glance on this and enjoy your reading. Hope you all might get benefited from it!


Package in java

What is package?

  • A Folder that is linked with java classes, interface ,and sub packages is called package.

What is need of package?

  1. Used to group related classes, interfaces and enums.
  2. Used to separate new classes from existed classes.
  3. By package we can create multiple classes with same name (remove naming collision)
  4. We can create user defined classes with predefined class names.

How to create package?

Syntax:-?package<package name>;

???????Ex: package p1;

Where we can declare package?

At the top of the java file or it should be the first statement of java file.

How many types of packages are their and what are they?

  1. Parent package.
  2. Sub-package.

==>The package (parent or sub) which is?already build-in predefine java file by the sun and other vendors, like??lang, awt, javax, swing, io, util etc.. Is called pre-define(parent and sub) package.?

==>The package define by us as per the requirement of project like package p1;?package p2; ..are known as user define(parent or sub) package.

?Default:- package statement is optional. If we define a class without package statement, then that class is said to be available in "default package "i.e.; current working directory.

---------//---------

Bullets points:-

  • In Every java program by default java.lang package will be automatically imported
  • Java support 2 types of packages (a)parent package and (b) sub package. The main folder we created for storing?the main functionality class is called parent package.
  • The sub folder created inside main solder for storing sub-functionality classes is called sub-package.
  • ?The parent package can be predefined or can be a user defined package?

Creation process of package in java file:-

  1. Create a program in normal text file and save it as " .java" extension .

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

2. Compiler does not create package physically in current working directory just with javac command. Package classes must be compiled with "-d" option to create package physically.

Syntax:- javac-d<path in which package should be copied> source filename.

For Example >javac -d . Example.java

With this command compiler creates package "p1" with "Example.class" and places it in current working directory. Operator "." represents current working directory.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

>javac -d D:\Program Example.java

3. With this command compiler creates package "p1" with "Example.java" in?????D:\Program folder.

Rule: Program folder must be existed in D drive before this program compilation, else it leads to CE.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

--------------------------------------------------------------------------

What is the functionality of "-d"?

Its actual functionality is creating package with the name mentioned in java file and moving all?.class files in that package, and finally storing that package in the given path.

  • We can use -d option to compiling normal java files. It means we can use -d option to compile a java file even though it doesn't have package statement.
  • The basic need of -d option is saving .class file in the given folder path.
  • If the java file contains package statement, -d option will create package folder, generate .class file in the package folder and then saves package folder in the given directory path.
  • If the java file doesn't contains package statement, -d option will save .class file directory inside the given folder path.

?Creating?another file in same package with different name:

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Test class file created in same package on given class path.

No alt text provided for this image

----------------------------/------------------------------

How Compiler change the code after providing package ?

After compilation?compiler replace class name and its constructor name with its packagename.classname. It is called fully qualified name

No alt text provided for this image
No alt text provided for this image

Note:-To execute java file belongs to package we must use package name to execute it -

>java p1.Example

To see compile generated .class we must use-

>javap Example.class

Why we must use package name in execution?

As you observed, in Example.class the class is changed as p1.Example. Since name is p1.Example, it must be executed with the same name means in execution we must use package name.?

Can we execute a class from current working directory that is placed in another directory?

No, it lead to exception "java.lang,NoClassDefFoundError"

No alt text provided for this image
No alt text provided for this image

Note:-If package is placed in another directory, we must update its path in Classpath environment variable, else it leads above exception.

Updating Classpath environment variable:-

  • We can update Classpath in 3 ways-

1. By using java command option "-cp"?or??"- classpath".

No alt text provided for this image
No alt text provided for this image

2. By using "Set Classpath" command

No alt text provided for this image
No alt text provided for this image

3. By using "Environment Variables window".

  • Since 1,2 approach are temporary?way to execute java file from other directories.?but the 3rd will make?you to execute java file anytime from all.

----------------------/--------------------

What Classloader working functionality?

  1. ClassLoader loads classes into JVM based on Classpath environment variable setup.
  2. Tp load class bytes into JVM it searches in the folders those are configured in Classpath environment variable. It searches all folders till it finds given class's ".class" file. If it not found in any one of the folder then it throws "NoClassDefFoundError" exception.
  3. If Classpath is not at all created, then it loads classes only from current working directory.
  4. If Classpath is created it is mandatory to place "." operator to load classes from current working directory.
  5. If the classpath environment variable has the character ";" not as a separator, it is treated as "." so that ClassLoader loads classes from current working directory.

When we are using a class from another class, should I compile that class first ?

  • No need to compile. Compiler automatically compiles the class. For example assume we are calling Example class method from Sample class method we can compiler Sample class directly without compiling?Example class.

1.???First it searches for that Example?class definition in sample.java, if not found.

No alt text provided for this image

?2.???It searches for Example.class in Sample class package, if not found.

3.???It searches for Example.java in Sample class package, if not found.

No alt text provided for this image

4.???Then compiler terminates Sample.java file?compilation by throwing CE: cannot find symbol

No alt text provided for this image

?5. if found in same defination sample.java

No alt text provided for this image

??compile and generated Sample.class file and also?Example.class file

No alt text provided for this image

6. Within Same?package?but package is already created and one of the?class is inside it -

No alt text provided for this image

7.???If Example.java is found, it searches for Example class definition in Example.java file. If it is found,???compiler compile?entire java file, it means it also compiles other class definitions?and generates those class's .class files. Else terminates Sample.java file compilation with above compilation error.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

?8.???If Example.class is found, it also searches for Example.java. If not found, compiler uses Example.class file directly.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

9.???If Example.java is also available, it checks modified time of both files, if Example.java file , modified date is greater than Example.class modified date, it compiles Example.java again for generating Example.class with its latest changed java code.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

=>Within in same package but classes are created at same folder and package is not created:-

No alt text provided for this image
No alt text provided for this image

Note:?The imported class must be compiled before the actual class.

No alt text provided for this image

?Note: Example class compiled and p1 package is created .

No alt text provided for this image

?Note: Inside p1 package we have Example.class file which is generated after the compilation of Example.java file

No alt text provided for this image

Note:- After Example.java file compilation, We will compile Sample.java file.

No alt text provided for this image

Note: Both .class file created in p1 package folder.

?10. Creating classes at Different package level

No alt text provided for this image
No alt text provided for this image

Note: If we not created package folder so ,?imported class should be compiled first

No alt text provided for this image

Note: p2 package is created with Example.class file inside it, after compilation of Example.java file

No alt text provided for this image

Note: p1 package is created with Sample.class file inside it,?after the compilation of Sample.java file

No alt text provided for this image

? -------------------------/-----------------------

Subpackage:- package inside another package, that means we created a java file and place it one of the package, in other word parent-child relation implementation-

No alt text provided for this image

Both the files are created where Sample.java belongs to p1 and Example.java belongs to p2 which is inside the p1.

No alt text provided for this image

Note:- if we were directly executing our main java file that is parent java file without executing sub package file, we will getting an error.

  • ?To overcome this first we should compile sub file that is Example.java to make file to be importable.

No alt text provided for this image

After compilation of Example.java p1 folder created and inside it p2 because Example.java belongs to p1.p2 and -d create both packages simultaneously , since Example.java belongs to p2 package therefore inside p2 Example.class file created.

No alt text provided for this image


No alt text provided for this image

Note: Executing main java file that is Sample.java, since p1 package folder is already created therefore Sample.class file will generated inside??existing package p1.?

No alt text provided for this image
No alt text provided for this image

?The program compiled successfully.

No alt text provided for this image

Note:- if we declare sub package java file as non-public, then it will treated as default and according to accessibility modifier default scope is with in package. Therefore we are getting error.

No alt text provided for this image
No alt text provided for this image

--------------------/------------------------

Practice=> Define Example class in Sample.java with "a" and "b" values as 15 and 16. Then compile and execute Sample.java file directly. Now Example.class is regenerated with Example class values defined in Sample.java- local preference.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Note:- here Sample$Example is the another .class file generated through sample.java, which representing the Example class file compiled code in the form of Sample$Example.class file

Now identifying the number of classes does created after compilation of?java file.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

?Can we create classes with predefined class name?

  • ?Yes, we can created user defined classes or custom classes with predefined class name.

No alt text provided for this image

Here in main method creation our created class is overlapping?the predefine class by which our main method is not able to execute.

  • So, to overcome this we have to define fully qualified name of the String class, so that main method can access it directly.

No alt text provided for this image
No alt text provided for this image

Then how can we differentiate these two classes?

  • By using package name if there is any class define locally with same predefined class name, we must access predefined class name with its package name. Else it is loaded from current working directory if Classpath environment variable is setup with "." operator.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

How to access over created method of same name as predefine class name.

We can use our created class by importing through package name were it is created.

No alt text provided for this image
No alt text provided for this image

How many way we can access other package classes from our package classes?

We can access them in two ways-

???1. By using fully qualified name

???2. By using import keyword

?What is "import" keyword?

  • Import keyword is used to "access" other package members from this package classes. Actually it does not import other package members into this package; instead it shows the path of the other package member to compiler and JVM.

We have 2 syntaxes to use import statement

No alt text provided for this image

What is the difference between above two import syntaxes?

  • First syntax allows Compiler & JVM to access all public members (classes, interfaces & enums) of that imported package, where as second syntax allows Compiler and JVM to access only that imported class.?

Rule: import statement must be placed before all class definitions, and after package statement.


How many import statements are allowed in one Java file?

  • In a java file "more than one import " statements and "only one package" statement are allowed.

Rule: To access package members from another package class its members must be declared as public, else it leads to compile time error while access that member.

Accessing other package members:-

No alt text provided for this image

Case 1:-If user class is also defined in same?package, import statement and fully qualified name is optional.

No alt text provided for this image
No alt text provided for this image

Case 2:- Is the class is using from another package, either import or fully qualified name must be used. Else it leads to CE: cannot find symbol.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Fully Qualified name:-

No alt text provided for this image

What is the benefit we get in using import statement over fully qualified name?

If we do not use import statement, we must use package name every wherever we are using class name or constructor. This code is considered as redundant code and also code is not readable. To solve this problem SUN introduced "import" concept So. If we use import statement we no need to use package name in referring class name and its constructor.

Give a?scenario where both import and fully qualified name should be used?

  • If?a class with same name is available in two packages,?to that class from packages we must use fully qualified name to differentiate class from another packaged class. In case if we use just import statements compiler throws ambiguous error in accessing that class.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Using Sub package members:-

  • WE must import sub package separately to access its members, because by importing parent package sub package members are not imported vice versa is also not possible.

Why sub package members are not imported, when we import parent package?

  • Because parent package may have more than one sub package, so compiler?and JVM cannot take decision from which sub package that class must be accessed.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Static import:-

This feature is introduced in java 5 to import static members of a class.

By using this feature we can access all

  • non-private static members without using class name from?other classes with in the package and
  • Protected and public members from outside package class members without using class name.

No alt text provided for this image

=>First syntax allows to call all static members of the class.

=>Second syntax allows only to call the imported static member.

Ex:-

?import p1.* ??

  • ?we can access all classes from p1 package.
  • By using this we are getting the classes which we are not using is called "code smells" that is not good practice.

?import p1.A; we can access only class A from p1 package.

import static p1.A.*;???

  • we can access all static members of class A from p1 package???
  • Using this import statement we cannot access non-static members. We cannot create object, we cannot develop subclass from A class.
  • for this purpose we must also write import statement separately for accessing class A as "import p1.A;"

Import static p1.A.a;

  • We can only access the static variable "a"
  • ?if "a" is a non-static variable it leads to CE: cannot find symbol "static a".

?Import static p1.A.a;

  • ?We can only access the static method "m1"
  • ??if "m1" is a non-static method it leads to CE: cannot find symbol??"static m1"

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

???Accessing protected member:-

No alt text provided for this image

Note :-the class members which have?protected keyword in its creation statement are called protested members. Those members can be accessible with in package from all classes, but from outside package only in subclass that too only by using subclass object(This rule is only for non-static protected members. Static protected members can be accessible by using same class name or by using subclass?name).

No alt text provided for this image

Solution:- Access protected members in sub class that to with regular import statement not by static import.

Most Restricted Accessibility modifier- Private>Default>Protected>Public

  • Access modifier determine whether other class can use a particular field or invoke a particular method. There are two level of access modifiers.

1.class level {public, default} 2. Member level{All four are used}

  • If class is declare as default and in that default class if we are having a public method. we can not access that public method in other class present in different package.

At member level- At the member level, we can also use the public or default( package- private) just as with class level, and with the same meaning

No alt text provided for this image


Accessing non-static as well static member through static import concept.

No alt text provided for this image

Note:-To solve above compile time errors we must also import class with normal import statement as?"import p1.A;"

No alt text provided for this image

If the current class also contains the imported static member, how can we differentiate both of them?

  • We must use fully qualified name of that static member that is "packagename.classname.staticmembername" else current class static member is used.

No alt text provided for this image
No alt text provided for this image

Solution:-

No alt text provided for this image

Practice Que- Write a program to print data without using class name System. You should use only "out.println()" to print "hi", "hello", "hru?".

No alt text provided for this image

Java Source file structure-

In a java file we can achieve package statement, import statement, interface, abstract class, concrete class, final class, main method class and documentation.

All these are organized as shown below according to coding standards and compiler rules

No alt text provided for this image

In-built packages-

  • SUN given packages are called in-built packages, and developer given packages are called custom or user defined packages.
  • SUN also organized all predefined classes, interfaces and enums is packages.
  • We have two root packages for in-built packages
  • They are - java and javax.
  • Java package has basic and fundamental or core classes and interface for design of java programming language.
  • Javax package has extension classes and interfaces.
  • ????????- javax stands for "Java extension"
  • Below diagram shows the Java SE important sub packages of java and javax packages.

No alt text provided for this image

Since in above approach we are facing one similar kind of problem that is , Compiling each and every file separately??before using to overcome such problem Auto compilation came into picture.

Auto Compilation

In a project , we no need to compile every class java file. When we compile main method class java file, all classes java file those are accessing from this main method class are automatically compiled by compiler software.

The phenomena or algorithm, compiling internally using classes java file??automatically by compiler software is called auto compilation.

  • If both .class and .java files are available , compiler will check time stamp of .java and .class file.
  • If .java file time stamp> .class time stamp then recompile Else compiler will directly uses existing .class file.

Auto-compilation algorithm?all the step?

  • Create the different package folders and save respective java files in it.
  • Created another package folder and create the main class java file.
  • Now call all the java files of different packages through main java file by using respective package import statements.
  • Now compile the main java file and you will get out puts.
  • Since, All the java files auto- compiled and generated .class file into their respective package folder.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

In above project we should not write main method in every class, its not compile time error or runtime error, it is a wrong design because the classes A ,B, C, and D must be executed from class test.

So we should not define main method in these 4 classes. We should define all 4 classes public, then only we can access them from Test class.

Rule:- Default class cannot be access from other package. To access the class from outside package it must an should be public type.

The valid way to arrange the java files-

In all above approach we are having a problem related to files, to easily differentiate them. That is separating .class file from .java is very tough for sending project executable file to client.

So the right approach is we must save java files and class files with package folder in separate directories as shown below

Procedure:-

1. Create project folder with two sub-directories????"src" and "bin".

2. Inside src folder create package folder with its java files.

?3. Compile the java file?with -d option by given bin?folder path.

4. Then -d option will create package folder inside bin directory with the .class files generated.

?5. Then change directory path to bin folder and?execute class files. (or) send bin folder all?packages with its class file to client.

??This is the right procedure of creating packaged java?files and class files.

?Not only we are following, eclipse also follows same procedure if we use eclipse IDE for java file creation, it automates this packages creation for java file and class files separately in src and bin folders.

No alt text provided for this image

?Example:-

No alt text provided for this image

Naming Convention of a package as per projects standards.

1. Inside package name all character should be small letters. And package name should be as short as possible.

  1. Package name should represent a group name generally functionality name like view, business logic, dao.
  2. In project we will create package name with as below

Company web domain reverse functionality.

No alt text provided for this image

Package statement Rule:- ?In a single?java file only one package statement is allowed also the package statement must be first statement the java file.

No alt text provided for this image

Conclusion:-

  • In Every java program by default java.lang package will be automatically imported
  • Default class cannot be access from other package. To access the class from outside package it must an should be public type.
  • To execute java file belongs to package we must use package name to execute it
  • If package is placed in another directory, we must update its path in Classpath environment variable, else it leads exception.
  • Static protected members can be accessible by using same class name or by using subclass?name
  • we can import multiple package in a single java file.
  • To not compile each and every file explicitly auto compilation came into picture.


Thankyou For Reading!

Published by:?Sakshi Agrawal

Date?:?April 23,2022

要查看或添加评论,请登录

Sakshi Agrawal的更多文章

  • SpringBoot Annotation

    SpringBoot Annotation

    Hello, to my all readers, Hope you all are enjoying your daily learning. Among my daily updates, Today I have come up…

  • Inner V/s Sub Classes In Java

    Inner V/s Sub Classes In Java

    Hello, to my all readers, Hope you all are enjoying your daily learning. Among my daily updates, Today I have come up…

  • What’s the variance amid an Abstract Class and Interface in Java?

    What’s the variance amid an Abstract Class and Interface in Java?

    Greetings to all my esteemed readers! I trust that each of you is enjoying a delightful reading experience. Please find…

  • Bitbucket

    Bitbucket

    Hello to my all Readers!..

  • Microservices

    Microservices

    Hello to my all Readers!..

  • My New Journey

    My New Journey

    Hello to my all Readers, Hope you are enjoying your reading. It's being quit long time I haven't shared the thoughts…

    2 条评论
  • Programs on operators

    Programs on operators

    Hello to all my Reader As you see my daily updates regarding my new work as a Python faculty in CCCGadarwara [Christ…

  • Python Session Overview

    Python Session Overview

    Hello to all my Reader As you see my daily updates regarding my new work as a Python faculty in CCCGadarwara [Christ…

  • Python Session Overview

    Python Session Overview

    Hello to all my Reader As you see my daily updates regarding my new work as a Python faculty in CCCGadarwara [Christ…

  • Python Session Overview

    Python Session Overview

    Hello to all my Reader As you see my daily updates regarding my new work as a Python faculty in CCCGadarwara [Christ…

社区洞察

其他会员也浏览了