Package with interface in java

Java — Packages

Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

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

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related.

Since the package creates a new namespace there won’t be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.

Creating a Package

While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package.

To compile the Java programs with package statements, you have to use -d option as shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder.

Example

Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.

Following package example contains interface named animals

/* File name : Animal.java */ package animals; interface Animal

Now, let us implement the above interface in the same package animals

package animals; /* 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(); >>

Now compile the java files as shown below −

$ javac -d . Animal.java $ javac -d . MammalInt.java

Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below.

Читайте также:  Import data txt python

Packages

You can execute the class file within the package and get the result as shown below.

Mammal eats Mammal travels

The import Keyword

If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax.

Example

Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class.

package payroll; public class Boss < public void payEmployee(Employee e) < e.mailCheck(); >>

What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package.

Note − A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration.

The Directory Structure of Packages

Two major results occur when a class is placed in a package −

  • The name of the package becomes a part of the name of the class, as we just discussed in the previous section.
  • The name of the package must match the directory structure where the corresponding bytecode resides.

Here is simple way of managing your files in Java −

Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java.

// File Name : Car.java package vehicle; public class Car < // Class implementation. >

Now, put the source file in a directory whose name reflects the name of the package to which the class belongs −

Now, the qualified class name and pathname would be as follows −

In general, a company uses its reversed Internet domain name for its package names.

Example − A company’s Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory.

Example − The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this −

. \com\apple\computers\Dell.java

At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class.

// File Name: Dell.java package com.apple.computers; public class Dell < >class Ups

Now, compile this file as follows using -d option −

The files will be compiled as follows −

.\com\apple\computers\Dell.class .\com\apple\computers\Ups.class

You can import all the classes or interfaces defined in \com\apple\computers\ as follows −

Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as −

\sources\com\apple\computers\Dell.java \classes\com\apple\computers\Dell.class

By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.

Читайте также:  Создать питон файл через терминал

The full path to the classes directory, \classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.

Say \classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in \classes\com\apple\computers.

A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.

Set CLASSPATH System Variable

To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell) −

To delete the current contents of the CLASSPATH variable, use −

To set the CLASSPATH variable −

  • In Windows → set CLASSPATH = C:\users\jack\java\classes
  • In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH

Источник

Packages & Interfaces in Java

A package is a mechanism to group the similar type of classes, interfaces and sub-packages and provide access control. It organizes classes into single unit.
In Java already many predefined packages are available, used while programming.
For example: java.lang, java.io, java.util etc.

Advantages of Packages

  • Packages provide code reusability, because a package has group of classes.
  • It helps in resolving naming collision when multiple packages have classes with the same name.
  • Package also provides the hiding of class facility. Thus other programs cannot use the classes from hidden package.
  • Access limitation can be applied with the help of packages.
  • One package can be defined in another package.

Types of Packages

There are two types of packages available in Java.

1. Built-in packages
Built-in packages are already defined in java API. For example: java.util, java.io, java,lang, java.awt, java.applet, java.net, etc.
2. User defined packages
The package we create according to our need is called user defined package.

Creating a Package

We can create our own package by creating our own classes and interfaces together. The package statement should be declared at the beginning of the program.
Syntax:

Example: Creating a Package

// Demo.java
package p1;
class Demo
public void m1()
System.out.println(«Method m1..»);
>
>

How to compile?
Syntax: javac –d directory javafilename
For Example: javac –d . Demo.java

How to run?
To run: java p1.Demo

Example: Program to create and use a user defined ackage in Java.

// Vehicle.java
package vehicles;
interface Vehicle
public void run();
public void speed();
>

//Bike.java
package vehicles;
public class Bike implements Vehicle
public void run()
System.out.println(«Bike is running.»);
>
public void speed()
System.out.println(«Speed of Bike: 50 Km/h»);
>
public static void main(String args[])
Bike bike = new Bike();
bike.run();
bike.speed();
>
>

Compile:
javac –d . Vehicle.java
javac –d . Bike.java

Читайте также:  Google docstring python example

Run:
java vehicles.Bike

Output:
Bike is running
Speed of Bike: 50 Km/h

The “import” keyword

The import keyword provides the access to other package classes and interfaces in current packages.
“import” keyword is used to import built-in and user defined packages in java program.
There are different 3 ways to access a package from other packages.

1. Using full qualified name

Example

class Demo extends java.util.Scanner
//statements
>

Example

import java.util.Scanner;
class Demo
// statements
>

Example

import java.util.*;
class Demo
// statements
>

Interface

  • Interface is similar to a class, but it contains only abstract methods.
  • By default the variables declared in an interface are public, static and final.
  • Interface is a mechanism to achieve full abstraction.
  • An interface does not contain any constructor.

interface InterfaceName
public void method1();
public void method2();
variableName = value;
>

Example: Sample of an interface

interface Employee
static final > static final String name = “ABC”;
void show();
void getSalary(double salary);
>

Extending interfaces

An interface has to extend another interface as it happens in class. It cannot implement another interface.

Example: Sample program for extending interfaces

interface Base
public void display ();
>
interface Derive extends Base
public void show ();
>

Implementing interfaces

  • A class implements an interface. After that, class can perform the specific behavior on an interface.
  • The implements keyword is used by class to implement an interface.

class ClassName implements interfacename
// body of class
>

Note: A class can implement more than one interface. Java can achieve multiple inheritances by using interface.

Example: Sample program to implements interface in Java

interface Results
final static float pi = 3.14f;
float areaOf(float l, float b);
>
class Rectangle implements Results
public float areaOf(float l, float b)
return (l * b);
>
>
class Square implements Results
public float areaOf(float l, float b)
return (l * l);
>
>
class Circle implements Results
public float areaOf(float r, float b)
return (pi * r * r);
>
>
public class InterfaceDemo
public static void main(String args[])
Rectangle rect = new Rectangle();
Square square = new Square();
Circle circle = new Circle();
System.out.println(«Area of Rectangle: «+rect.areaOf(20.3f, 28.7f));
System.out.println(«Are of square: «+square.areaOf(10.0f, 10.0f));
System.out.println(«Area of Circle: «+circle.areaOf(5.2f, 0));
>
>

Output:
Area of Rectangle: 582.61
Are of square: 100.0
Area of Circle: 84.905594

Example: Sample program to implements multiple inheritance

interface Vehicle
<
void run();
>
interface Bike extends Vehicle
<
void stop();
>
public class Demo implements Bike
<
public void run()
System.out.println(«Vehicle is running.»);
>
public void stop()
System.out.println(«Bike is stop.»);
>
public static void main(String args[])
<
Demo obj = new Demo();
obj.run();
obj.stop();
>
>

Marker Interface

An interface which does not contain any fields and methods is known as marker or tag interface. It is an empty interface.

For example Serializable, EventListener, MouseListner, Remote, Cloneable etc.

Example:
package java.util;
public interface EventListner
>

Differences between Abstract class and Interface

Abstract class Interface
It cannot support multiple inheritances. Interface supports multiple inheritances.
It contains both abstract and non abstract method. It contains only abstract method.
Abstract class is the partially implemented class. Interface is fully unimplemented class.
It can have main method and constructor. It cannot have main method and constructor.
It can have static, non-static, final, non-final variables. It contains only static and final variable.

Источник

Оцените статью