Package and interface example

Assignment Problem:
Create a class named Circle which can take radius as constructor parameter, and has methods which calculates and returns diameter, circumference and surface area. Write another class named MainCircle, which has main method, and creates an object of Circle, and invokes all methods of Circle class, and print the return values?

Solution:

package p2;

public interface ICircle {
public final float pi=3.14f;
   public float getDiameter();
   public float getcircumference();
   public  float getarea();    
}
package p1;
import p2.ICircle;
public class CircleImpl implements ICircle{
        float radius;
    public CircleImpl(float radius){
        this.radius=radius;
    }
    public float getDiameter(){
        float diameter=2*radius;
        System.out.println("The diameter is: "+diameter);
        return diameter;
    }
    public float getcircumference(){
        float circumference=2*pi*radius;
        System.out.println("The circumference is: "+circumference);
        return circumference;
    }
    public float getarea(){
        float area=pi*radius*radius;
        System.out.println("The area is: "+area);
        return area;
    }
}

Below is main method, which creates object of CircleImpl class, and invokes its methods

package p3;
import p1.CircleImpl;
public class MainCircle {
    public static void main(String[]args){
CircleImpl obj=new CircleImpl(3f);
obj.getDiameter();
obj.getcircumference();
obj.getarea();
    }
}

Click here to download this code, on Eclipse
You may also like to read:
What is a package
What are access specifiers

What is static import? What are advantages and disadvantages of static import?

By static importing a class, all static members in that class can be directly used. This avoids using class name for each and every static member. Also, note that even pre defined classes like System,etc… can be static imported.

static import was introduced in Java 1.5 version
Below is an example of static import. As shown in below example, Test is a class in com.p1 package, and Test class has few static members.

package com.p1;

public class Test {
	public static float PI = 3.14f;
	
	public static double getDiameter(double radius)
	{
		return radius/2;
	}
	
	public static double getCircumference(double radius)
	{
		return 2*PI*radius;
	}
	
	public static double getSurfaceArea(double radius)
	{
		return PI*Math.pow(radius, 2);
	}
	
}

In below code snippet, since com.p1.Test.* is imported using static, it is possible to use static members of com.p1.Test class directly, without using class name.

package com.p2;

import static com.p1.Test.*;

public class SIDemo {
	public static void main(String args[])
	{
	double diameter = getDiameter(5.68);
		
	System.out.println("Diameter is: "+diameter);
		
	double s_area = getSurfaceArea(3.86);
		
	System.out.println("Surface Area is: "+s_area);
		
	System.out.println("PI value considered is:"+PI);
	}
}

Can we use multiple static import

Yes, we can use multiple static import statement in a java file. How ever, ensure that there is no ambiguity in the static members of static imported classes.

package com.p1;

public class Test {
	public static float PI = 3.14f;
	
	public static double getDiameter(double radius)
	{
	return radius/2;
	}
	
	public static double getCircumference(double radius)
	{
	return 2*PI*radius;
	}
	
	public static double getSurfaceArea(double radius)
	{
	return PI*Math.pow(radius, 2);
	}
	
	public static void display()
	{
	System.out.println("display() in com.p1.Test");
	}
}

package com.p3;

public class Abc {
	public static void display()
	{
	System.out.println("display() in com.p3.Abc");
	}
}

package com.p2;

import static com.p1.Test.*;
import static com.p3.Abc.*;

public class SIDemo {
	public static void main(String args[])
	{
	double diameter = getDiameter(5.68);
		
	System.out.println("Diameter is: "+diameter);
		
	double s_area = getSurfaceArea(3.86);
		
	System.out.println("Surface Area is: "+s_area);
		
	System.out.println("PI value considered is:"+PI);
		
	//below method call causes compiler error, as display() method
	//is available in both the classes, com.p1.Test and com.p3.Abc
	//display();
	}
}

Disadvantages of static import

Below are disadvantages of static import
1.This may arise readability issues.
2.It may also cause ambiguity, when same member is declared in more than one static imported classes.

You may also like to read:
What is use of static members
Can we have more than one static block
Role of static method in abstract class
how to use packages in Java

What is JAR File and How to create JAR File

A JAR File, stands for Java Archive file. Like ZIP file, JAR is compressed file format, which is used to share software resources required for Java Applications. For example Hibernate, Struts, Spring,etc… provide their framework implementation through multiple JAR files. Similarly you can provide Jar files to your clients, or other Teams dependent on your Classes or packages. Even JDBC driver is provided as a Jar file. A Jar file may contain
1. bunch of .class files
2. any other resource files, like images, icons,etc… required by .class files

Also note that a jar file can have multiple packages or sub packages.

How to create JAR file in Eclipse

Below are the steps involved in creating jar file in Eclipse IDE.
1. Create a Java Project
2. Add class Files
3. Build the Project, do Testing
4. Right click on Project, and Select Export

export jar file
export jar file

5. In Export Window, select java, then JAR file, then Next button.
create-jar
create-jar

6. Now Below JAR File Specification window appears. Select various options, based on your requirement.
Select or unselect appropriate checkbox to specify if you want to Export generated class files and resources or Export Java source files and resources as well.

jar-file-specification
jar-file-specification

Browse to select a location for the JAR file, which will get created.

Select or unselect, Compress the contents of the JAR file checkbox.
Select or unselect, Overwrite existing files without warning checkbox. If you unselect this checkbox, then you will be prompted to confirm the replacement of each file that will be overwritten.

In this way you can create JAR file, out of your class files, and other required resources, and distribute it.

You may also like to read:

How to Compress and Uncompress file in Java


How to create a Jar file in a Netbeans Project?
How to create Jar file, in run time, using Java program?
How to add an external Jar file to a Eclipse Project?
How to add an external jar file to a Netbeans Project?

Purpose of a package, in Java

What is a package?

A Package is set of Classes, interfaces or sub packages.

Advantage of package

Below are advantages of packages
1. To avoid name collisions between classes or interfaces. Using different packages it is possible to have Classes or interfaces with same name.
2. Improves Modularity of Applications. As application development, is done across various Teams spread across various organizations, it is advantage to have each software module or layer in a package, and each sub module may further have sub package.
3. Another advantage of packages is, packages provides one more level of accessibility. Class members or classes with default or no access specifier, are accessible only within, current package.

All public classes and interfaces can be accessed by other packages also.
All classes and interfaces with default or none access specifier, can be accessed only within current package.

Below is diagram showing two packages com.java652 and com.p1. The package com.java652 has two classes WeatherDetails and CityDetails. The package com.p1 has one class StateDetails and an interface. objects of classes in different packages interact with each other, to perform required functionality.

What is Java Package
Java Package

Keywords used for packages





Below are keywords used in packages
1. package
package keyword is used to specify to which package, current java source file belongs to. There can be only package statement in a file. package statement need to be first statement in the file.
2. import
import keyword is used to specify that classes or interfaces of other packages need to be used in current java file. There can be multiple import statements, in a single file.

Also note that a separate folder is created with package name as folder name. And all class and interface files belonging to this package, are in this folder.

Download Package example(Eclipse Project)

For each sub package, one sub folder is created, under the main folder.

How to create package

how to create package, manually

When you develop java project using command line, and simple text editor, you need to manually create the package.
That means you need to manually create folders, and sub folders, for packages and sub packages, accordingly. Place java source file in corresponding folders or sub folders.

How to create package on Eclipse

As shown in below picture,
Right click on project, for which you want to create a package.
Now select New, then select package, then fill the package name like com.java652
To create class in this package, right click on package, select New, then select Class, then fill the class name.

how to create package in eclipse
how to create package in eclipse

How to create package on Netbeans

As shown in below picture,
Right click on project, for which you want to create a package.
Now select New, then select Java Package, then fill package name
To create class in this package, right click on package, select New, then select class.

how to create package in netbeans
how to create package in netbeans

you may also like to read:
How many Access specifiers in Java?
Can a abstract class have static method

Access Specifier and Scope

Below are Access Specifiers supported in Java.
1. private
2. public
3. protected
4. default or none

private, public, protected are Access specifiers, which can be used only for members(data members and member methods) of a class.

private members can be accessed only within the class.

public members can be accessed with the class, other classes in current package, classes in other package.

protected members can be accessed within the class, and in the immediate derived class.

members with no access specifiers can be accessed within the class, and other classes only within current package.

Lifetime of variables

Lifetime of a variable, depends on the place where it has been declared.

Life time of Data members or instance variables is same as the object, in which they exist. An object is destroyed by garbage collector Java when there are no more reference to that object.

Local Variables:
Local variables are the variables declared in the method body. Local variable are available within method body until method returns.

Arguments or Parameters:
Arguments or Parameters are passed to constructor or methods, and are available until the constructor or method returns.

Also variables can be declared in a block(Eg. if, else block,etc…), within a method. Such variables are available only within the block where they have been declared.

Below is an example code snippet:

class Test1
{
	int i,j; //data members or member variables or instance variables

	Test1()//constructor
	{
	i = 20;
	j = 11;

	System.out.println("Test1() Constructor");
	}

	void add() //member methods
	{
	int k; //local variable i..e not a member variable of Test1 class
	//NOTE: k cannot be accessed from object of Test1 class
	k = i+j;
	System.out.println("Add Result is:"+k);
	}

	void sub()
	{
	int l = i-j; //l is local variable
	System.out.println("Sub Result is:"+l);
	}
}

public class ClassDemo {
//execution starts from here
public static void main(String args[])
{
//obj is local object
	Test1 obj; //declaring object reference
	obj=new Test1(); //creating object of Test1 class
	obj.add(); //invoking add() method of Test1 class, using object obj

	obj.sub();
}
}

You may also like to read:
purpose of static block
what is for each loop, in java