Thursday, 4 June 2015

Java defining an Interface

The general form of an interface is like class as shown below.

modifiers interface <interfac_name>

{ modifiers return_type method1(parameter-list);

modifiers return_type method2(parameter-list);

.

modifiers type final_var1 = value1;

modifiers type final_var2 = value2;

.

}

1. Modifiers for Top-Level Interface

The only modifiers that can be used with the top-level interfaces are abstract and public.

Even if we do not use abstract modifier, the interface is implicitly declared to be abstract so use of modifier abstract is redundant.

The visibility of a top-level interface can be either package or public just like top-level class. If no visibility modifier is used then the visibility of the interface is assumed to be package.

2. Interface Methods

Methods declared in an interface have no body. They end with a semicolon after the parameter list. They are, essentially, abstract methods and there can be no default implementation of any method specified within an interface.

All the methods declared in an interface have two modifiers, which are implicit:

abstract public method(parameter-list);

Methods are always abstract, which means they do not have any body and have public access.

All the methods declared in an interface are instance methods to be defined in the sub-classes.

We cannot declare static methods in interfaces.

3. Interface Data Members

We can define only constants in the interfaces.  All the variables in an interface are implicitly public, final and static meaning they cannot be changed by the implementing class. They must also be initialized with constant value.

Variables in an interface have implicit modifiers as shown below:

public static final int x = 10;

The variable x is public, static and final. It means it is a static variable with public access. The variable is also declared final, which means that it must be assigned a value at the time of declaration, which cannot be modified later on. The keyword final is like const in C/C++.

Example: The following program defines an interface for a stack i.e. it abstracts the public part of the stack.

interface StackInterface

{ void push(int x);

int pop();

}

The interface specifies that the stack has just two operations and any class sub-classing (implementing) this interface must provide bodies of push() and pop() methods.

Java Interface introduction

The purpose of the interface is to separate a class’s interface from its implementation. Interface just defines what a class must do without saying anything about the implementation. Interfaces define only method signatures and they do not have any instance variables. Interfaces are very good tool for designing as you can just define signatures of public methods without going into
implementation details, which are left for the person implementing the interface.

Using the keyword interface, you can fully abstract a class‘s interface from its implementation. That is, using interface, you can specify what a class must do, but not how it does it.

Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. In practice, this means that you can define interfaces, which do not make assumptions about how they are implemented. Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces.

To implement an interface, a class must create the complete set of methods defined by the interface. However, each class is free to determine the details of its own implementation. By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple methods” aspect of polymorphism.

Interfaces are designed to support dynamic method resolution at run time. They disconnect the definition of a method or set of methods from the inheritance hierarchy. Since interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in terms of class hierarchy to implement the same interface. This is where the real power of interfaces is realized.

Note: Interfaces add most of the functionality that is required for many applications, which would normally resort to using multiple inheritance in a language such as C++.

Sunday, 31 May 2015

Java Importing packages

We discuss this concept with reference to previous example. Given that packages exist and are a good mechanism for compartmentalizing diverse classes from each other, it is easy to see why all of the built in Java classes are stored in packages.

There are no core java classes in the unnamed default package; all of the standard classes are stored in some named package.

Since classes within packages must be fully qualified with their package name or names, it could become tedious to type the long dot-separated package path name for every class you want to use. For this reason, Java includes the import statement to bring certain classes, or entire package into visibility. Once imported, a class can be referred to directly, using only its name.

Note: The import statement is a convenience to the programmer and is not technically needed to write a complete Java program. If you are going to refer to a few dozen classes in your application, however, the import statement will save a lot of typing.

In Java source file, import statements occur immediately following the package statement. (if it exists) and before any class/interface definitions.

The geneal form of import statement:

import pkg1 [.pkg2] [.pkg3].[classname | *];

Note: 

1. The star form may increase compilation time. However, the star form has absolutely no effect on the run-time performance or size of your classes.

2. All of the standard Java classes included with Java are stored in a package called java. The basic language functionality is stored in a package inside of the java package called java.lang. Normally, you have to import every package or class that you want to use, but since Java is useless without much of the functionalities in java.lang, it is implicitly imported by the compiler for all programs. This is equivalent to the following line being at the top of all of your programs:

import java.lang.*;

3. If a class with the same name exists in two different packages that you import using the star form, the compiler will remain silent, unless you try to use one of the classes. In that case, you will get a compile-time error and have to explicitly name the class specifying its package.

4. Any place you use a class name, you can use its fully qualified name, which includes its full package hierarchy. When a package is imported, only those items within the package declared as public will be available to non-subclasses in the importing code.

Java visibility of class members

Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods. Packages act as containers for classes and other subordinate packages. Class act as container for data and method code. The class is Java’s smallest unit of abstraction. Because of the interplay between classes and packages, Java addresses five categories of visibility for class members:

1. Visibility within the class

2. Visibility in sub-classes in the same package

3. Visibility in non-sub classes in the same package

4. Visibility in sub-classes in different package

5. Visibility in classes that are neither in the same package nor are sub classes.

A top-level class or interface has only two possible access levels: default and public. When a class is declared public, it is accessible by any other code. If a class has default access, then it can only be accessed by other code within the same package.

The visibility of class members is summarized in the following table:


Note: The member visibility has meaning only if the class is visible. If visibility modifier of the class is default then even public members of the class will be visible only within the package.

Example:

Protection.java

package p1;

public class Protection

{

int n = 1;

private int n_pri = 2;

protected int n_pro = 3;

public int n_pub = 4;

public Protection()

{

System.out.println("Base Constructor");

System.out.println(n);

System.out.println(n_pri);

System.out.println(n_pro);

System.out.println(n_pub);

}

}

To compile: javac –d . Protection.java

Derived.java

package p1;

class Derived extends Protection

{

public Derived()

{

 System.out.println(n);

System.out.println("Derived Constructor");

//System.out.println(n_pri);

System.out.println(n_pro);

System.out.println(n_pub);

  }

}

To compile: javac –d . Derived.java

SamePackage.java

package p1;

class SamePackage

{

public SamePackage()

  {

Protection p = new Protection();

System.out.println("Same Package constructor");

System.out.println(p.n);

//System.out.println(p.n_pri);

System.out.println(p.n_pro);

System.out.println(p.n_pub);

}

}

To compile: javac –d . SamePackage.java

Protection2.java

package p2;

class Protection2 extends p1.Protection

{

Protection2()

{

System.out.println("Protection2 Constructor");

//System.out.println(n);

//System.out.println(n_pri);

System.out.println(n_pro);

System.out.println(n_pub);

}

}

To compile: javac –d . Protection2.java

OtherPackage.java

package p2;

class OtherPackage

{

OtherPackage()

{

p1.Protection p = new p1.Protection();

System.out.println("OtherPackage Constructor");

//System.out.println(p.n);

//System.out.println(p.n_pri);

//System.out.println(p.n_pro);

System.out.println(p.n_pub);

}

}

To Compile: javac –d . OtherPackage.java

Test1.java

package p1;

class Demo

{

public static void main(String args[])

{

Protection ob1 = new Protection();

Derived ob2 = new  Derived();

SamePackage ob3 = new SamePackage();

}

}

To Compile: javac –d . Test1.java

Output:

Base Constructor1234
Base Constructor1234
Derived Constructor134
Base Constructor1234
Same Package Constructor134

Test2.java

package p2;

class Demo

{

public static void main(String args[])

{

Protection2 ob1 = new Protection2();

OtherPackage ob2 = new OtherPackage();

}

}

To Compile: javac –d . Test2.java

Output:

Base Constructor1234
Protection2 Constructor
34
Base Constructor1234
OtherPackage Constructor
4

Java Packages

If no package name is specified in any java file then the class is part of the unnamed package. This requires that every class must have a unique name to avoid collisions. After a while, without some way to manage the namespace, you could run out of convenient descriptive names for individual classes.

You also need some way to be assured that the name you choose for a class will be reasonably unique and not collide with class names chosen by other programmers.

Java provides a mechanism for partitioning the class name space into more manageable chunks. This mechanism is the package.

The package is both a naming and visibility control mechanism.
You can define classes inside a package that are not accessible by code outside that package.
You can also define class members that are only exposed to other members of the same package.
This allows your classes to have intimate knowledge of each other, but not expose that knowledge to the rest of the world.

Defining a package

To create a package, include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name and is called un-named package.

This is the general form of package statement:

package pkg_name;

Java uses file system directories to store packages. Remember that case is significant, and directory name must match the package name exactly. More than one file can include the same package statement.

You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general form of a multi-leveled package statement is shown here:

package pkg_name1 [.pkg_name2] [.pkg_name3];


A package hierarchy must be reflected in the file system of your Java development system.

For example a package declared as:

package java.awt.image;

needs to be stored in java/awt/image, java\awt\image, or java:awt:image on your Unix, Windows, or Macintosh file system, respectively.

A global naming scheme has been proposed to use the reverse Internet domain names to uniquely identify packages.

For example the apache’s domain name is www.apache.org. So to store classes in package tomcat, preferably you should use the package hierarchy:

org.apache.tomcat

which would be unique.

A package hierarchy represents an organization of Java classes and interfaces. It does not represent the source code organization of the classes and interfaces. Each Java source file (also called compilation unit) can contain zero or more definitions of classes and interfaces, but the compiler provides a separate class file containing the Java byte code for each of them. A class or interface can indicate that its java byte code be placed in a particular package, using a package declaration.

At most one package statement can appear in a source file, and it must be the first statement in the unit.

Note that this scheme has two consequences. First, all classes and interfaces in a source file will be placed in the same package. Secondly, several source files can be used to specify the contents of a package.

Finding packages and CLASSPATH

As discussed, packages are mirrored by directories. This raises an important question. How does the Java run-time system know where to look for packages that you create?

There can be two approaches:

First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if your package is in the current directory, or a subdirectory of the current directory, it will be found.

Second, you can specify a directory path or paths by setting the CLASSPATH environment variable. For example, consider the following package specification:

package mypack;

In order for a program to find mypack, one of the two things must be true. Either the program is executed from a directory immediately above mypack, or CLASSPATH must be set to include the path to mypack.

Jar File

If you are developing a complex system or using third party libraries then instead of creating a directory hierarchy for class files you can use .jar files by including them in the CLASSPATH.

The JVM searches for the packages and classes in .jar file as it does searches in the file system.
Instead of .jar file you can also use a .zip file created by any popular software like winzip, winrar etc. Jar files can be created using jar utility that is part of JDK. To include the current directory and all the sub-directories below it in a jar file give the following command:

jar -cf myjar.jar *

here, c stands for creating a new .jar file.

         f stands for name of the .jar file.

The above command will create myjar.jar file in the current folder.

Example:

package mypack;

public class MyProg

{ public static void main(String args[])

{ System.out.println("Yes, Its working!");

}

}

To compile the following program give following command:

C:\totest>javac -d . MyProg.java

Here -d is used to create a directory ‘mypack’ in the current folder and put the class file in this folder automatically. When we compile the program, ‘mypack’ directory is created in the current folder (which is assumed to be c:\totest).

We can run above program in following different ways:

1. Running from the current directory: 

Give the following command from the directory where the package directory is created i.e from folder c:\totest.

java mypack.MyProg

This is because, MyProg file is part of package mypack.

Output:

Yes, Its working!

2. Running using classpath:

Give the following command at the command prompt:

SET CLASSPATH = %CLASSPATH%;C:\totest;

Then give the following command from any directory/folder:

java mypack.MyProg

3. Running by specifying classpath as parameter

Give the following command:

 java –classpath c:\totest mypack.MyProg

4. Running using jar file: Go to C:\totest folder and give the following command:

 jar –cf myjar.jar mypack (or jar -cf myjar.jar mypack)

and then give the following command:

java -classpath c:\totest\myjar.jar mypack.MyProg

After creating the .jar file, you can also set the classpath as follows:

set classpath=%classpath%;c:\totest\myjar.jar

Note: you can use –d option to copy the class file in any desired folder. For example, use the following command to create folder ‘mypack’ in C:\myclasses:

javac –d C:\myclasses MyProg.java

This will create a folder mypack below myclassses, if not already present and put the MyProg.class file in it.