Skip to content

Chapter 3 : Interface and Package

Saket Khopkar edited this page Jan 5, 2022 · 1 revision

Multiple Inheritance:

  • Single derived class with multiple base classes is called as multiple inheritance.
  • Multiple inheritance allows us to join the features of number of existing classes as a starting point for deriving new class.

How it is achieved in Java?

  • Java classes cannot have more than one super classes. But in most of the real time application multiple inheritance is required. So Java provides an alternate approach knows as interface to achieve multiple inheritance.

Interfaces:

  • Interfaces are similar to the classes with the lack of instance variables and their instance methods are declared without any body. Once it is defined any number of classes can implement an interface.
// Syntax:  
access-specifier interface InterfaceName
{
    data_type final_variable1; // final & static variables
    data_type final_variable2;
    :
    data_type final_variableN;
    return_type method_name1(parameter_list); // abstract methods
    return_type method_name2(parameter_list);
    :
    return_type method_nameN(parameter_list);
}
// Multiple Inheritance in Java using Interfaces.
interface Student
{
    final static int rollno = 12;
    final static String name = "Disha";
    void display();
}
interface Exam
{
    final static int m1 = 76;
    final static int m2 = 84;
    void show();
}
class Result implements Student, Exam
{
    int total;
    public void display()
    {
        System.out.println("Roll No: " + rollno);
        System.out.println("Name: " + name);
    }
    public void show()
    {
        System.out.println("Marks 1: " + m1);
        System.out.println("Marks 2: " + m2);
    }
    void output()
    {
        total = m1 + m2;
        System.out.println("Total: " + total);
    }
}
class InterfaceDemo
{
    public static void main(String args[])
    {
        Result r = new Result();
        r.display();
        r.show();
        r.output();
    }
}
// Output: Rollno: 12
// Name: Disha
// Marks 1: 76
// Marks 2: 84
// Total: 160
  • Here, interface is the keyword and InterfaceName is any valid java identifier.
  • Access-Specifier is either public or not used. When no access specifier is included, then default (friendly) access specifier results, and interface is only available to other methods of the package in which it is declared.
  • By default all variables in interface are final and static, which needs to assign an constant value which cannot be changed.
  • Methods declaration contains only list of methods without body. These are abstract methods.

Features / Characteristics:

  1. All the variables in an interface are final and static by default.
  2. Interfaces contain only methods declaration without its body (abstract methods).
  3. Some class must implement the interface in order to write body of the methods declared inside the interfaces.
  4. Several interfaces can be combined together into a single interface, thus provides an idea of multiple inheritance.
  5. Interfaces can extend other interfaces, but SubInterfaces cannot define the methods declared in the SuperInterfaces.
  6. An interface cannot extend classes.
  7. An interface can have only abstract methods and constants.

Need:

  1. Java classes cannot have more than one super classes. But in most of the real time application multiple inheritance is required. So, Java provides an alternate approach knows as interface to achieve multiple inheritance.
  2. Interfaces can also be used to declare set of constants that can be used in different classes.

Extending Interfaces:

  • Interfaces can be extended like classes. That is, an interface can be SubInterfaced from other interfaces.
  • This new SubInterface can inherit all the members of SuperInterface in the same manner like subclasses.
// Syntax: 
interface SubInterface extends SuperInterface
{
    body of SubInterface
}
Example: interface ItemConstants
{
    int code = 1001;
    String name = "Fan";
}
interface Item extends ItemConstants
{
    void display ();
}
  • Here, Item interface would inherit both constants code and name. The variables name and code are considered as final and static even though the final and static keywords are not present.
// Combining several interfaces into a single interface:
interface ItemConstants
{
    int code = 1001;
    String name = "Fan";
}
interface ItemMethods
{
    void display ();
}
interface Item extends ItemConstants, ItemMethods
{
    ---------------
    ---------------
}

Here,

  1. SubInterfaces cannot define the methods declared in the SuperInterfaces.
  2. An interface cannot extend classes.
  3. When an interface extends two or more interfaces they are separated by comma.

Implementing Interfaces:

  • Interface can contain final and static constants and abstract methods declarations without body. So, interfaces must be implemented by some class in order to write the body of its methods.
Syntax: 
class ClassName [extends SuperClass] implements interface1, interface2…
{
body of ClassName
}
  • This shows that a class can extend another class (it is optional hence shows in [ ] brackets) while implementing interfaces.
  • When a class implements more than one interfaces it is separated by commas.
  • Here ClassName should implements all the methods define in the implemented interfaces. Otherwise class becomes abstract class and cannot be instantiated.
// Program to calculate area of circle in which implementation of interface as class type.
interface Area
{
    final static float PI=3.14f;
    float compute (float x, float y);
}
class Rectangle implements Area
{
    public float compute (float x, float y)
    {
        return (x*y);
    }
}
class Circle implements Area
{
    public float compute (float x, float y)
    {
        return (PI*x*x);
    }
}
class InterfaceTest
{
    public static void main (String args[])
    {
        Rectangle rect = new Rectangle();
        Circle cir = new Circle();
        Area ar;
        ar = rect;
        System.out.println("Area of Rectangle = " + ar.compute(10,20));
        ar=cir;
        System.out.println("Area of Rectangle = " + ar.compute(10,0));
    }
}
// Output: Area of Rectangle = 200
/ Area of Circle = 314

Accessing Interface Variables:

  • Interfaces can be used to declare set of constants that can be used in different classes. This is similar to creating headers files in C++ to contain a large number of constants.
  • Since such interfaces do not contain methods, there is no need to worry about implementing any methods.
  • The constant values will be available to any class that implements the interface.
  • The values can be used in any methods, as a part of any variable declaration, or anywhere where we can use a final value.
// Example: 
interface A
{
    int m = 10;
    int n = 50;
}
class B implements A
{
    int x = m;
    void methodB (int size)
    {
        ----------
        ----------
        if (size < n)
            ----------
    }
}

Nesting of Interfaces:

  • Interfaces can be nested similar to a class. An interface can be nested within:
  1. Another interface
  2. A class
  • Nesting of interface is also called as interface within interface or interface within class or inner interface. Enclosing interface or class is called as outer interface or outer class.
  • Nesting of interface leads to the easy maintaining and accessing the group of related interfaces.
  • The nested interface cannot be accessed directly. To access nested interface, it must be referred by the outer interface or class.
  • Rules for nesting interface:
  1. Nested interface must be public if it is declared inside the interface.
  2. Nested interface can have any access modifier if it is declared inside the class.
  3. Nested interfaces are declared as static implicitly.
// Syntax:
interface InterfaceName
{
    __________
    __________
    interface nested_interface_name
    {
        __________
        __________
    }
}
// Program to demonstrate interface inside interface.
interface Showable
{
    interface Message
    {
        void msg();
    }
}
class Test implements Showable. Message
{
    public void msg()
    {
        System.out.println("This is Nested Interface Inside Interface");
    }
}
class NestDemo1
{
    public static void main(String args[])
    {
        Showable. Message m = new Test();
        m.msg();
    }
}
// Output: This is Nested Interface Inside Interface

Packages:

  • Packages are the collection of functionally related classes and interfaces. Packages act as “containers” for classes.
  • Packages are another way of achieving reusability in Java.
  • If we want to use the classes from other programs without actually copying them into program then this can be achieved in Java by using packages.
  • The concept of package is very similar to class libraries in other languages.

Benefits / Advantages / Need:

  1. The classes contained in the packages of other programs can be easily reused.
  2. In packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have the same name.
  3. Packages provide a way to hide classes thus preventing other programs or packages from accessing classes that are meant for internal use only.
  4. Packages provide a way for separating designing from coding.
  5. Packages provide the reusability beyond the programs.
  6. With the help of package we can reuse the classes and interfaces, so it will reduce size and time.

Java API Packages:

  1. java.lang :- It include language support classes. These are the classes that Java compiler itself uses and therefore they are automatically imported. It include classes for Primitive Data Types Integer, Float and String, Math, Thread, Exception, etc.
  2. java.util :- It include language utility classes such as Vector, Date, HashTable, etc.
  3. java.io :- It include input / output related classes such as InputStreamReader, DataInputStream, BufferedReader, IOException, etc.
  4. java.awt :- It include classes for implementing GUI . It has Window, Font, Color, Button, Menu, Checkbox, etc, classes.
  5. java.net :- It include classes for networking and communication between client and server. It has Socket, ServerSocket, InetAddress, etc. classes.
  6. java.applet :- It includes classes for creating and implementing Applets such as Applet.
  • Packages in Java can be named using standard Java naming rules listed below:
  1. Packages begin with lowercase letters, so that packages can be distinguished from class name.
  2. All class names begin with an uppercase letters.
  3. Method names begin with lowercase letters, but if it contains more than one word then subsequent word’s first letter must be uppercase.
  4. Every package name must be unique. Duplicate names will cause run time error. Java is best for Internet; many users work on Internet, so chances of using duplicate names are high. To avoid this problem, we can use domain names as prefix to preferred package names.
  • Example: cbe .psg. mypackage
  • Here, cbe is city name and psg denotes organization name.
  • It is possible to create a hierarchy of packages within packages by separating levels with dots.

Steps for creating the package:

  1. Declare the package at the beginning of a source file using the form: package packagename;
  2. Define the class that is to be put in the package and declare it public.
public class ClassName
{
Class body
}
  1. Create a subdirectory under the directory where the main source files are stored. Name of the subdirectory must match with the name of package to be created.
  2. Store the listing as the ClassName.java file in the subdirectory created.
  3. Compile the file. This creates .class file in the subdirectory.

Note:

  • Java supports package hierarchy. This is done by specifying multiple names in a package statement separated by dots. package firstpackage . secondpackage;
  • This approach allows us to group related classes into a package and then group related packages into a larger package.
  • A Java package file can have more than one class. In such cases, only one of the classes may be declared public and that class name with .java extension is the source file name.
  • In above case java creates independent .class files for those classes.

Access specifiers / visibility modes:

  • Private: Anything that is declared as private can be used within a class only.
  • Friendly (default): Anything that is declared as friendly can be access within a package only.
  • Protected: Anything that is declared as protected can be access in all classes of same package and sub classes in other packages.
  • Public: Anything that is declared as public can be access everywhere. If we declare anything as a public in a package it means that can be used in same package and outside of the package.

Static Import:

  • This feature eliminates the need of qualifying a static member with the class name.
  • We can use static import statement to import classes from packages and use them without qualifying the package.
  • We can also use the static import statement to import static members from classes and use them without qualifying class name. Syntax: import static package_name . subpackage_name . Classname.staticmember_name; or import static package_name . subpackage_name . ClassName . *;
  • Without static import feature, we had to use the static member with qualifying class name. For example, double cirarea = Math.PI * radius * radius; In the above code, PI is the static member of the class Math. So it is used with class name Math.
  • If we use static member in an interface and we need to use it in a class, then we have to implement that interface in the class. Now, we can use this feature to import the interface into the class. Consider following example:
public interface Salary_incrment
{
public static final double manager = 0.5;
public static final double clerk = 0.2;
}
  • Here, let us assume that the interface is available in the sub-package employee_details of the employee package. If we need to access the interface, we can import the interface using the static import statement as follows:
import static employee.employee_details.Salary_increment;
class Salary_hike
{
public static void main(String args[])
{
double manager_salary=manager.Manager_current_salary;
double clerk_salary=clerk.Clerk_current_salary;
-----------
-----------
}
}
  • Thus we can use static members in the code without qualifying the class name or interface name. Also the static import feature reduces the redundancy of using the qualifying class name or interface name while using static members.
// Program to demonstrate static import feature.
import static java.lang.Math.*;
class MathOp
{
    void circle(double r)
    {
        double area = PI*r*r;
        System.out.println(“Circle Area = “ + area);
    }
    public static void main(String args())
    {
        MathOp obj = new MathOp();
        obj.circle(2.3);
    }
}
// Output: Circle Area = 16.619025