Saturday, January 11, 2020

Packages

Java Packages


Package


Packages in java are important for avoiding naming conflicts and ease to find types in a Java Project. A Package is a unit of software that can be distributed independently and the collection of these packages can form an entire application. Several interrelated classes, interfaces, sub-packages, and additional resource files(like images) are grouped to gather to create a package.


Benefits of Packages are


Easier to find and use types
  • To avoid naming conflicts by creating namespaces
  • To provide access control
  • To provide a protection domain for developing application frameworks
  • To provide better space management

    Creating a Package


    You need to put a package statement with the name of the package at the top of every source file that contains the types (Classes, Interfaces, enumerations, and Annotation types) that you want to include in the package


    package figure;
    There can one and only one package statement in source file and it must be the first line of the source file.


    Packages Naming Conventions

Generally, the following conventions are followed to name a package.
  • Package names are written in small letters.
  • Organizations use their reversed Internet domain name to begin their package names, for example, com.example.mypack for a package named mypack created by a programmer at example.com. 






Access control with packages


Packages are also very important in terms of access protection. For example, we have two classes A and B, and two packages X and Y.
The access protection can be summarised in the following table.


 Table for access specifiers


A
B
X
Y
 public  
Y
Y
Y
Y
protected
Y
Y
Y
N
no specifier
Y
Y
N
N
private
Y
N
N
N


For example,

package com.example.figure;
public class Circle {
}
/****************************************/
package com.example.figure;
public class Rectangle extends Shape{
int ht,wd;
public Rectangle(int ht, int wd) {
    super();
    this.ht = ht;
    this.wd = wd;
}

@Override
public void displayArea() {
    System.out.println("Area="+ht*wd);
}
}

/***********************************************/
package com.example.figure;
public abstract class Shape {
public abstract void displayArea();

}

/***************************************/
package com.example.ui;
//to import classes
//import com.example.figure.Rectangle;
//to import complete package

import com.example.figure.*;
public class Demo {
    public static void main(String[] args) {
           Rectangle r=new Rectangle(15, 20);
            r.displayArea();

}
}

/***************************************/

Video Tutorial