Nothing Special   »   [go: up one dir, main page]

Package and Interface

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 29

Packages and Interfaces

Packages
• A java package is a group of similar types of classes, interfaces and sub-
packages.
• Packages are containers for classes that are used to keep the class name
space compartmentalized.
• 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.
• Package in java can be categorized in two form, built-in package and user-
defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
Advantage 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.
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 classed which defines
primitive data types, math operations). This package is automatically imported.
2) java.io: Contains classed 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.
• To import a package
import package.name.*;
import java.util.*;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Scanner to take input from the user object
OUTPUT
Enter You Name AAA
Scanner myObj = new Scanner(System.in);
Your Name IS : AAA
String userName;
// Display message
// Enter Your Name And Press Enter
System.out.println("Enter You Name");
// Reading the integer age entered using
// nextInt() method
userName = myObj.nextLine();
// Print and display
System.out.println("Your Name IS : " + userName);
}
}
Defining a Package
•To create a package is quite easy: simply include a package command
as the first statement in a Java source file.
•Any classes declared with in that file will be long to the specified
package.
•The package statement defines a name space in which classes are
stored.
• If you omit the package statement, the class names are put into the
default package, which has no name.
package pkg;
•Here, pkg is the name of the package.
• Now in order to create a package in java follow the certain steps as
described below:
• First We Should Choose A Name For The Package We Are Going To
Create And Include. The package command In The first line in the java
program source code.
• Further inclusion of classes, interfaces that is required in the package
can be made in the package. For example, the below single statement
creates a package name called “FirstPackage”.
• The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
• For example, a package declared as
package java.awt.image;
• needs to be stored in java\awt\image in a Windows environment.
// Name of package to be created
package FirstPackage; Procedure:
1. To generate the output from the above
// Class in which the above created package belong to program
class Welcome { Command: javac Welcome.java
2. The Above Command Will Give Us
// main driver method Welcome.class File.
Command: javac -d . Welcome.java
public static void main(String[] args) 3. So This Command Will Create a New
{ Folder Called FirstPackage.
Command: java
// Print statement for the successful FirstPackage.Welcome
Output: The Above Will Give The Final
// compilation and execution of the program Output Of The Example Program
System.out.println(“Geeks For Geeks.."); Geeks For Geeks
}
}
// Name of package to be created
package data;
// Class to which the above package belongs
public class Demo {
// Member functions of the class- 'Demo'
// Method 1 - To show()
public void show() 1. To generate the output from the above
program
{ Command: javac Demo.java
// Print message 2. This Command Will Give Us a Class File
System.out.println("Hi Everyone"); Command: javac -d . Demo.java
3. So This Command Will Create a New Folder
} Called data.
// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
} }
// Name of the package
import data.*;
// Class to which the package belongs
class ncj {
// main driver method
public static void main(String arg[]) Command: javac Demo.java
Command: java ncj // To Run This File
{
// Creating an object of Demo class
Hi Everyone
Demo d = new Demo(); Hello
// Calling the functions show() and view()
// using the object of Demo class
d.show();
d.view();
}
}
Finding Packages and CLASSPATH
1. 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.
2. Second, you can specify a directory path or paths by setting the
CLASSPATH environmental variable.
3. Third, you can use the -classpath option with java and javac to
specify the path to your classes.
Access Protection
An Access Example
Importing Packages
• Since classes within packages must be fully qualified with their package name or names, it could
be come tedious to type in the long dot-separated package path name for every class you want
to use.
• For this reason, Java includes the import statement to bring certain classes, or entire packages,
into visibility.
• Once imported, a class can be referred to directly, using only its name.
• If you are going to refer to a few dozen classes in your application, however, the import
statement will save a lot of typing.
• In a Java source file, import statements occur immediately following the package statement (if it
exists)and before any class definitions.
import pkg1[.pkg2].(classname|*);
• Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.).
• There is no practical limit on the depth of a package hierarchy, except that imposed by the file
system.
• Finally, you specify either an explicit class name or a star(*), which indicates that the Java
compiler should import the entire package.
import java.util.Date;
import java.io.*;
• All of the standard Java classes included with Java are stored in a package called
java.
• The basic language functions are stored in a package inside of the java package
called java.lang.
• Normally, you have to import every package or class that you want to use, but
since Java is useless without much of the functionality in java.lang, it is implicitly
imported by the compiler for all programs.
• import java.lang.*;
• If a class with the same name exists in two different packages that you import
using the star form, the compiler will remain silent, unless you try to use one of
the classes.
• In that case, you will get a compile-time error and have to explicitly name the
class specifying its package.
• It must be emphasized that the import statement is optional.
• Any place you use a class name, you can use its fully qualified name, which
includes its full package hierarchy.
Interfaces
• 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.
• Why use Java interface?
• Defining an Interface
• An interface is defined much like a class. This is the general form of an
interface:

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Java Interface Example

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();
}
}
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}
Multiple inheritance in Java by interface

• If a class implements multiple interfaces, or an interface extends


multiple interfaces, it is known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Default Method in Interface
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Static Method in Interface
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Nested Interface in Java

• An interface can have another interface which is known as a nested


interface. We will learn it in detail in the nested classes chapter. For
example:
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
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();
}
}
Abstract class Interface
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.
3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

You might also like