Unit: 9 Packages and Interface

By Haitomns G

Package

Packages are container for classes. Interface and subclasses. The package is the both anime and a visibility control mechanism. This means that a few classes can be clubbed together and given the name. In this manner, user can manipulate method, and they wear a single object. The package, if no name is specified, then the class name is automatically put into default package, which does not have a package or Java way of programming a number of related classes or interface together into single unit. And that means package act at a container for classes.

Advantages of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Java foundation Packages:

Java provides a large number of classes grouped into different packages based on their functionality.

The six foundation java packages are:

  1. Java.lang

Container classes for primitive type, string, math function, thread, and exception.

  • Java.util

Container classes such as vectors, #(hash) table, data, etc.

  • Java.io

Stream classes for I/O

  • Java.awt

Classes for implementing GUI, windows, buttons and menus.

  • Java.net

Classes for networking

  • Java.applet

Classes for creating and implementation applets

Creating Packages:

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management.

Some of the existing packages in Java are −

java.lang − bundles the fundamental classes

java.io − classes for input, output functions are bundled in this package

Syntax:

package mypackage;

 public class A

{

            Class body;

}

Class B

{

            Class Body;

}

Example:

//save as Simple.java 

package mypack; 

public class Simple{ 

 public static void main(String args[]){ 

    System.out.println(“Welcome to package”); 

   } 

Accessing class from package:

There are two ways of accessing the class store in package.

  1. Import package.class;
  2. Import package.*;

Example:

  1. import my package.classA;
  2. import my package.classB;

Finding Packages and CLASSPATH

As just explained, 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? The answer has three parts. 

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

Second, you can specify a directory path or paths by setting the CLASSPATH environmental variable. 

Third, you can use the -classpath option with java and javac to specify the path to your classes.

For example, consider the following package specification:

package MyPack;

In order for a program to find MyPack, one of three things must be true. Either the program can be executed from a directory immediately above MyPack, or the CLASSPATH must be set to include the path to MyPack, or the -classpath option must specify the path to MyPack when the program is run via java.

When the second two options are used, the class path must not include MyPack, itself. It must simply specify the path to MyPack. For example, in a Windows environment, if the path to MyPack is

image 1

then the class path to MyPack is 

image 2

CLASSPATH is actually an environment variable in Java, and tells Java applications and the Java Virtual Machine (JVM) where to find the libraries of classes. These include any that you have developed on your own.

An environment variable is a global system variable, accessible by the computer’s operating system (e.g., Windows). Other variables include COMPUTERNAME, USERNAME (computer’s name and user name).

In Java, CLASSPATH holds the list of Java class file directories, and the JAR file, which is Java’s delivered class library file.

Access Protection

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.

Classes act as containers for data and code. The class is Java’s smallest unit of abstraction. Because of the interplay between classes and packages, Java addresses four categories of visibility for class members:

  • Subclasses in the same package
  • Non-subclasses in the same package
  • Subclasses in different packages
  • Classes that are neither in the same package nor subclasses  Anything declared public can be accessed from anywhere in the project.
  • Anything declared private cannot be seen outside of its class. 
  • When a member does not have an explicit access specification, it is visible to subclasses as well as to other classes in the same package. This is the default access. 
  • If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected.
image 3
Access Protection Table

When a class is public, it must be the only public class declared in the file, and the file must have the same name as the class.

Interface

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. It cannot be instantiated just like the abstract class.

There are mainly three reasons to use interface. They are given below.

  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

Declare an interface

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

Syntax:

interface <interface_name>

    // declare constant fields 

    // declare methods that abstract  

    // by default. 

Relationship Between Classes and Interfaces

As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface.

image 4
Class and Interface Relation

Example

In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.

interface printable {

    void print();

}

class A6 implements printable {

    public void print() {

        System.out.println(“Hello”);

    }

    public static void main(String args[]) {

        A6 obj = new A6();

        obj.print();

    }

}

Output:

Hello

Implementing Interfaces

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

Example

/* File name : MammalInt.java */

public class MammalInt implements Animal {

   public void eat() {

      System.out.println(“Mammal eats”);

   }

   public void travel() {

      System.out.println(“Mammal travels”);

   }

   public int noOfLegs() {

      return 0;

   }

   public static void main(String args[]) {

      MammalInt m = new MammalInt();

      m.eat();

      m.travel();

   }

}

This will produce the following result −

Output

Mammal eats

Mammal travels

Java Nested Interface

An interface, i.e., declared within another interface or class, is known as a nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred to by the outer interface or class. It can’t be accessed directly.

Points to remember for nested interfaces

There are given some points that should be remembered by the java programmer.

  • The nested interface must be public if it is declared inside the interface, but it can have any access modifier if declared within the class.
  • Nested interfaces are declared static.

Syntax of nested interface which is declared within the interface

interface interface_name {

    …

    interface nested_interface_name{ 

     … 

    }

}

Example:

interface Showable {

    void show();

    interface Message {

        void msg();

    }

}

class TestNestedInterface1 implements Showable.Message {

    public void msg() {

        System.out.println(“Hello nested interface”);

    }

    public static void main(String args[]) {

        Showable.Message message = new TestNestedInterface1();// upcasting here

        message.msg();

    }

}

Output:

hello nested interface

Interface Variables

An interface defines a protocol of behavior and not how we should be implemented. A class that implements an interface adheres to the protocol defined by that interface.

Interface variables are static because java interfaces cannot be instantiated on their own. The value of the variable must be assigned in a static context in which no instance exists.

The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned. In other words, interfaces can declare only constants, not instance variables.

Syntax:

interface interfaceName{

   // Any number of final, static variables

   datatype variableName = value;

   // Any number of abstract method declarations

   returntype methodName(list of parameters or no parameters);

}

Extend Interfaces in Java

An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. An interface extends another interface like a class implements an interface in interface inheritance.

A program that demonstrates extending interfaces in Java is given as follows:

Example

interface A {

   void funcA();

}

interface B extends A {

   void funcB();

}

class C implements B {

   public void funcA() {

      System.out.println(“This is funcA”);

   }

   public void funcB() {

      System.out.println(“This is funcB”);

   }

}

public class Demo {

   public static void main(String args[]) {

      C obj = new C();

      obj.funcA();

      obj.funcB();

   }

}

Output

This is funcA

This is funcB

Also, Read

  1. Unit-4 Operator
  2. Unit-5 Control Statements
  3. Unit-6 Introducing Classes
  4. Unit: 7 A Closer Look at Methods and Classes
  5. Unit: 8 Inheritance

Haitomns G. is a desktop, android, and web developer based in Nepal. He has worked on building several websites, apps, and softwares for clients and independent projects. He is experienced in C, C++, C#, Java, Python, SQL, HTML, CSS, PHP, and JavaScript.

Leave a Comment

Slide to prove you're not a bot/spammer *