Packages and Interfaces

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Java Packages

A java package is a group of similar types of classes, interfaces and sub-


packages. A mechanism to encapsulate a group of classes, sub packages and
interfaces.
Package in java can be categorized in two form, built-in package and user-
defined package.

The already defined package like java.io.*, java. lang.* etc., are known as built-
in packages. There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.

User-defined packages: User-defined packages in Java are essentially packages


that are defined by the programmer. Whenever we want to add a class to the
package, we have to mention the package name and the “package” keyword at
the top of the program.
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 conflicts.
Built-in Packages

These packages consist of a large number of classes which are a part of


Java API.Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes (e.g classes which defines primitive
data types, math operations). This package is automatically imported.
2) java.io: Contains classes for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button;menus etc).
6) java.net: Contain classes for supporting networking operations.
The keyword package is used to create a package in java.

Syntax: package package-name;

package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
Steps to create User-defined Packages
Step 1: Creating a package in java class. Just write a package by following its
name.
package example1;

Step 2: Include class in java package, but remember that class only have one package
declaration.
package example1;
class gfg
{
public static void main(Strings[] args)
{
-------function--------
}
}
Step 3: Now the user-defined package is successfully created, we can import it into other
packages and use functions
In this example, we’ll create a user-defined package and function to print a message for the
users.

package example;

public class gfg {

public void show()


{
System.out.println("Hello");
}

public static void main(String args[])


{
gfg obj = new gfg();
obj.show();
}
}
In the below-mentioned example, we’ll import the user-defined package “example”
created in the above example. And use the function to print messages.

import example.gfg;

public class GFG {


public static void main(String args[])
{
gfg obj = new gfg();
System.out.println(obj.show());
}
}
How to access a package from another package?

There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.

The import keyword is used to make the classes and interface of


another package accessible to the current package.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using packagename.classname

If you import package.classname then only declared class of this


package will be accessible.
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using fully qualified name

If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But you
need to use fully qualified name every time when you are accessing
the class or interface.

It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Illustration of user-defined packages:
Creating first package:
package package_name; Making use of both the created packages:
import package_one.ClassTwo;
public class ClassOne {
import package_name.ClassOne;
public void methodClassOne() {
System.out.println("Hello there its
public class Testing {
ClassOne");
public static void main(String[] args){
}
ClassTwo a = new ClassTwo();
}
ClassOne b = new ClassOne();
Creating second package:
a.methodClassTwo();
b.methodClassOne();
package package_one;
}
}
public class ClassTwo {
public void methodClassTwo(){
System.out.println("Hello there i am
ClassTwo");
}
}
If you import a package, all the classes and interface of that
package will be imported excluding the classes and interfaces of
the subpackages. Hence, you need to import the subpackage as
well.

Sequence of the program must be package then


import then class.
Important points:
1. Every class is part of some package.
2. If no package is specified, the classes in the file goes into a special unnamed
package (the same unnamed package for all files).
3. All classes/interfaces in a file are part of the same package. Multiple files can
specify the same package name.
4. If package name is specified, the file must be in a subdirectory called name (i.e.,
the directory name must match the package name).
5. We can access public classes in another (named) package using: package-
name.class-name
Access Modifiers in Java
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.

There are four types of Java access modifiers:


Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Access within class within outside package outside
Modifier package by subclass package
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private
The private access modifier is accessible only within the class.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Protected

The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor.
It can't be applied on the class.
It provides more accessibility than the default modifer.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Public
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Interface in Java
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.

An interface is a description of the actions that an object can do... for example
when you flip a light switch, the light goes on, you don't care how, just that it
does.
Using the keyword interface, you can fully abstract a class’ 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 that don’t 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.
Why use Java interface?

There are mainly three reasons to use interface.

• It is used to achieve abstraction.

• By interface, we can support the functionality of multiple inheritance. Since java


does not support multiple inheritance in case of class, by using interface it can
achieve multiple inheritance .

• It can be used to achieve loose coupling. Loose coupling in Java means that the
classes are independent of each other.
How to 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:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
When no access specifier is included, then default access results, and the
interface is only available to other members of the package in which it is
declared.
When it is declared as public, the interface can be used by any other code.
In this case, the interface must be the only public interface declared in the
file, and the file must have the same name as the interface.

name is the name of the interface, and can be any valid identifier. Notice
that the methods that are declared have no bodies. They end with a
semicolon after the parameter list. They are, essentially, abstract methods;
there can be no default implementation of any method specified within an
interface. Each class that includes an interface must implement all of the
methods.
Variables can be declared inside of interface declarations. They are
implicitly final and static, meaning they cannot be changed by the
implementing class. They must also be initialized.

All methods and variables are implicitly public.

An example of an interface definition. It declares a simple interface that


contains one method called callback( ) that takes a single integer
parameter.

interface Callback {
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that
interface. To implement an interface, include the implements clause in a class
definition, and then create the methods defined by the interface. The general
form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated
with a comma. If a class implements two interfaces that declare the same
method, then the same method will be used by clients of either interface. The
methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature
specified in the interface definition.
An example class that implements the Callback interface shown
earlier.

class Client implements Callback {


// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}

Notice that callback( ) is declared using the public access specifier.


It is both permissible and common for classes that implement interfaces to
define additional members of their own. For example, the following version of
Client implements callback( ) and adds the method nonIfaceMeth( ):

class Client implements Callback {


// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
The 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.

You might also like