Menus

Jul 29, 2016

Package and Interface in Java

Course contents:
  1. Content
  2. Defining a package
  3. Access protection
  4. Importing packages
  5. Defining interfaces
  6. Applying interfaces 

An interface is similar to a class that can contain only constants, group of related method signatures, and nested types. There is no method body that is we cannot define methods inside the interface.

Interfaces cannot be instantiated they can only be implemented by classes or extended by other interfaces. Those classes that implement the interface must define the methods that are declared inside the interface. An interface is defined much like class.

The general syntax of interface definition is
Access specifier interface interfacename
{
 return type method-name1(parameter-list);
 return type method-name1(parameter-list);
 return type method-name1(parameter-list);
 return type method-name1(parameter-list);
 type variable-name1 = value;
 type variable-name2 = value;
 ……………..
 …………….
 return type methodnameN(parameter-list);
 type variable-nameN = value;
}
Here, access specifier is optional. When an access sepecifier is not specified then interface is only available to members of the package in which it is declared. When it is declared as public, the interface can be used by any other code.


Interface is keyword. Interfacename is the name of the interface. The methods that are declared inside interface are terminated by semicolon and all methods declared in an interface are implicitly public, so the public modifier can be omitted.

All the variables declared inside interface are public, final and static, so these keywords are also omitted. They cannot be changed by any classes that implement the interface.
Eg.
public interface area
{
 static float pi = 3.14;
 float compute(float x, float y);
 void show();
}

Extending interface
Interface can also be extended that is an interface can be sub-interfaced from other interfaces. The new sub-interface will inherit all the members of the superinterface in the manner similar to subclass.

This is achieved using the keyword extends. The general syntax of interface extension is:
interface subinterface extends superinterface1, superinterface2,…….
{
 Body of name2
}
Here, sub-interface inherits all the properties of the super interfaces. In an interface we can extends more than one interface. This cannot be done in inheritance.
Eg.
interface Itemconstants
{
 int code = 10;
 String name = “Ram”;
}
interface Item extends ItemConstants
{
 void display();
}

Here, the interface Item would inherit both the constants code and name into it. We can several interfaces together into a single interface.
Eg.
interface Itemconstants
{
 int code = 10;
 String name = “Ram”;
}
interface ItemMethods
{
 void display();
}
Interface Item extends ItemConstants, ItemMethods
{
 ………….
 …………..
}

Implementing Interface
Once an interface has been defined, one or more classes can implement the interface. To implement an interface, implements clause is used in class definition and then define methods that are declared by interface.

The general form of interface implementation is as follows class classname extends superclass implements interface1, inter face2,……..
{
 Body of the class
}

This shows that a class can extend another class while implementing interfaces. When a class implements more than one interface, they are separated by a comma.

WAP that demonstrate the concept of interface implementation
interface Area
{
 final static float pi = 3.14F;
 float compute(float x , float y);
}

class Rectangle implements Area// implement Area interface
{
 public float compute(float x , float y)
 {
 return(x*y);
 }  
}

class Circle implements Area
{
 public float compute(float x , float y)
 {
 return(pi*x*y);
 }
}

class InterfaceTest
{
 public static void main(String args[])
 {
 Rectangle r = new Rectangle();
 Circle c = new Circle();
 Area a;
 a = r;
 System.out.println("Area of Rectangle = " + a.compute(12,10));
 a = c;
 System.out.println("Area of cirle = " + a.compute(12,0));
 }  
}

Points to remember
- Interfaces are allowed to extend to other interfaces.
- Sub-interfaces cannot define the methods declared into super interfaces.
- Interface extends two or more interfaces, they are separated by commas.
- Sub-interface contains all the method and variables in superinterface as well as its own variables and methods.
- Interface cannot extend class.
- Class implements the derived (sub-interface) interface to define all the methods.

Package
Package is a collection of related classes and/or interfaces. The collection or grouping is done according to functionality. This is used for both naming and visibility control. We can define classes inside a package that are not accessible by a code outside that package.

We can also define class members that are only accessible to other members of the same package. The purpose of organizing classes into the package has following benefits:
  1. The classes contained in the packages of other programs can be easily reused.

  1. Classes can be unique compared with classes in other package that is tow classes in two different packages can have same name. They may be referred by their fully qualified name.

  1. Package provide a way to hide classes.

Java API package
Java API provides large number of classes grouped into different packages according to functionality. Following are the java built-in package:
1. lang(java.lang)
This package contains language support classes. These are classes that java compiler itself uses and therefore they are automatically imported. They include classes for primitive types, strings, math functions, threads and exceptions.

2. util
this package contains language utility classes such as vectors, hash tables, random numbers, date etc.

3. io
This package contains input/output support classes. They provide facilities for the input and output of data.

4. awt
This package contains set of classes for implementing graphical user interface. They include classes for windows, buttons, lists, menus and so on.

5. net
This package contains classes for networking. They include classes for communicating with local computers as well as with internet servers.

6. Applet
This package contains classes for creating and implementing applets.

Defining package
The following steps are used to create own package:
1. Declare a package at the beginning of a file using the form package packagename;

2. Define the class that is to be put in the package and declare it public.
Eg.
package MyPackage;
public class Calculator
 public int Add(int first, int second)
 {
 return (first + second);
 }
 public int Subtract(int first, int second)
 {
 return (first - second);
 }
 public int Multiply(int first, int second)
 {
 return (first * second);
 } 
 public float Divide(int first, int second)
 {
 return (first / second);
 }
}

3. Create a subdirector y under the director y where the main source files are stored. Where name of subdirectory is same as package name.
Eg. E:\java\MyPackage

4. Store the listing as the classname.java file in the subdirectory created.
i.e save above class Calculator class with extension .java inside
E:\java\MyPackage\

5. Compile the file. This creates .class file in the subdirectory.
Compile calculator.java which creates calculator.class file inside.
E:\java\MyPackage

6. To use such package include E:\java path in CLASSPATH environment variable.

Adding multiple class in a package
Following are the steps to add multiple classes inside the package:
1. Decide the name of package

2. Create the subdir ectory with this name under the directory where main source files are stored.

3. Create classes that are to be placed in the package in separate source files and declare the package statement Package packagename;
at the top of each source file.

4. Switch to the subdirectory created earlier and compile each sour ce file. When completed, the package would contain .class files of all the source files.
Eg:
It is simple to add a class to an existing package. Consider the following package

Package p1;
Public class A
{
 //body of A
}

The package p1 contains one public class named A. suppose we want to add another class B to this package. This can be done as follows:
1. Define the class and make it public.

2. Write a package statement
package p1;
 before the class definition as follows:
package p1;
public class B
{
 //body of B
}

3. Save this as B.java file under the directory p1

4. Compile B.java file. This will create a B.class file and place it in the directory p1.

5. Now the p1 package contains both the classes A and B.

Program that demonstrate use of multiple user defined package in a single class
1. Create a package named Package1 as
package Package1;
public class ClassA
{
 public void displayA()
 {
 System.out.println("Inside class A of package1");
 } 
}

Save this file with name ClassA.java inside E:\java\Package1, where package name and folder name should be same. Compile this file.

2. Create another package Package2 as:
package Package2;
public class ClassB
{
 int m = 10;
 public void displayB()
 {
 System.out.println("Inside class B of package 2");
 System.out.println("m = " +m);
 } 
}
Save this file with name ClassB.java inside E:\java\Package2, where package name and folder name should be same. Compile this file.

3. Create main java file as follows:
import Package1.ClassA;
 import Package2.*;
class PackageTest1
{
 public static void main(String args[])
 {
 ClassA objA = new ClassA();
 ClassB objB = new ClassB();
 objA.displayA();
 objB.displayB();
 }
}
Output:
Inside class A of package1
Inside class B of package2
m =10

Access protection.
Access modifier
Public
Protected
Private
No-modifier
Access location




Same class
Yes
Yes
Yes
Yes
Subclass in same package
Yes
Yes
No
Yes
Other class in same package
Yes
Yes
No
Yes
Subclass in other package
Yes
Yes
No
No
Non-subclass in other package
Yes
No
No
No

Fig: visibility of field in a class

No comments:

Post a Comment

Contact Form

Name

Email *

Message *