0% found this document useful (0 votes)
14 views59 pages

PackagesAndInterfaces

The document provides an overview of packages and interfaces in Java, detailing how to define packages, manage visibility, and implement interfaces. It explains the structure of packages, access protection, and the use of import statements, as well as the characteristics and implementation of interfaces. Additionally, it includes examples of creating and using packages and interfaces, demonstrating their functionality in Java programming.

Uploaded by

speriwal21024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views59 pages

PackagesAndInterfaces

The document provides an overview of packages and interfaces in Java, detailing how to define packages, manage visibility, and implement interfaces. It explains the structure of packages, access protection, and the use of import statements, as well as the characteristics and implementation of interfaces. Additionally, it includes examples of creating and using packages and interfaces, demonstrating their functionality in Java programming.

Uploaded by

speriwal21024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Packages and Interfaces

• packages are container for classes.

• used to keep the class name compartmentalized.

• package is both a naming and visibility control mechanism.


C:\Program Files (x86)\Java\jdk1.8.0_101\jre\lib\rt\java
Defining a package

▪ To create a package include a package command as the first statement.

▪ Any classes declared within that file will belong to the specified package.

▪ If package statement is not included, then class names are put into the default
package, which has no name.
General form :

package pkg;

Ex: package MyPackage;

We can create a hierarchy of package.

General form
package pkg1[.pkg2[.pkg3]];

Ex: package java.awt.image.


Finding packages and CLASSPATH

• First, by default, the Java run-time system uses the current working directory as its
starting point.

• if our package is in the current directory, or a subdirectory of the current directory,


it will be found.

• Second, we can specify a directory path or paths by setting the CLASSPATH


environmental variable.

• We can use –classpath option with java and javac to specify the path to our class.
Finding packages and CLASSPATH
Example

Consider the following package specification.

package MyPack;

In order for a program to find MyPack, one of the 3 things must be true.

• Either the program is executed from a directory immediately above MyPack.

• CLASSPATH must be set to include the path to MyPack.

• The –classpath option must specify the path to MyPack when the program is run via
java.
When second two options are used, the classpath must not include MyPack itself.
It must specify the path to MyPack.

For ex: in windows if the path is to MyPack is


C:\MyPrograms\java\MyPack

Then the classpath to MyPack is


C:\MyPrograms\java
A Short Package Example
package MyPack;
class prg
{
public static void main(String args[])
{
System.out.println(“first program to illustrate package”);
}
}

Name the above file as prg.java and put it in a directory called MyPack.
Next compile the file, make sure that resulting class file is also in MyPack.

Run the program using


java MyPack.prg
Access Protection
Example has two packages p1 , p2 and five classes.

▪ first package defines three classes: Protection, Derived and


SamePackage.

▪ The first class defines four int variables in each of the legal protection
modes.

▪ The variable n is declared with the default protection, n_pri is private,


n_pro is protected, and n_pub is public.
▪ The second class, Derived, is a subclass of Protection in the same package p1.
- This grants Derived access to every variable in Protection except for n_pri.

▪ The third class, SamePackage, is not a subclass of Protection, but is in the same
package and also has access to all but n_pri.
package p1
package p2
class protection
class derived2 extends p1.protection
{
{

}
class derived extends protection
}
{
class otherpackage
{
}
class samepackage
{
}
}
Protection.java
package p1;
public class Protection
{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
Derived.java
package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("n = " + n);
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
SamePackage.java
package p1;
class SamePackage
{
SamePackage()
{
Protection p = new Protection();
System.out.println("n = " + p.n);
// System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
Protection2.java

package p2;
class derived2 extends p1.Protection
{
Protection2()
{
// System.out.println("n = " + n);
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
OtherPackage.java

package p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();

// System.out.println("n = " + p.n);


// System.out.println("n_pri = " + p.n_pri);
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
Importing Packages
import statement to bring certain classes, or entire packages, into visibility.

Once imported, a class can be referred to directly, using only its name.

This is the general form of the import statement:

import pkg1[.pkg2].(classname|*);

import java.util.Date;
import java.io.*;
import java.awt.*;

import statements occur immediately following the package statement (if it exists) and before
any class definitions.
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.

We have to import every package or class that we 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.

This is equivalent to the following line being at the top of all of our programs:

import java.lang.*;
import statement is optional.

import java.util.*;
class MyDate extends Date
{

The same example without the import statement looks like this:

class MyDate extends java.util.Date


{

}
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterBroker;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.Vm;

class prg
{
public static void main(String args[])
{
Host h = new Host();
Vm v = new Vm();
}
}
Interface
• An interface is basically a kind of class.

• Like classes, interfaces contains methods and variables.

• Difference : interfaces define only abstract methods and final variables.

• Interface do not specify any code to implement the methods.

• Interfaces are designed to support dynamic method resolution at runtime.


Defining an interface
access interface name
{
return-type method-name1(parameter-list);
…………….
return-type method-nameN(parameter-list);

type final-varname1 = value;


…………….
type final-varnameN = value;
}

Methods are declared with no bodies.


All variables are implicitly final and static.
interface interfacename
{
variable declaration
method declaration
}

Example:
interface item
{
static final int code=1000;
void display();
}
Example

interface Callback
{
void callback(int param);
}
Implementing Interfaces

access class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}
class Client implements Callback
{
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}

When we implement an interface method, it must be declared as public.


We can also define additional members.

class Client implements Callback


{
public void callback(int p)
{
System.out.println("callback called with " + p);
}
void nonIfaceMeth()
{
System.out.println(“Added method");
}
}
Accessing Implementations Through Interface References
class TestIface
{
public static void main(String args[])
{
Callback c = new Client();
c.callback(42);
}
}

c can be used to access the callback() method, it can not access any other
members of the Client class.
// Another implementation of Callback.

class AnotherClient implements Callback


{
public void callback(int p)
{
System.out.println("Another version of callback“+(p+10));
}
}
class TestIface2
{
public static void main(String args[])
{
Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);

c = ob; // c now refers to AnotherClient object


c.callback(42);
}
}
OUTPUT: callback called with 42
another version of callback 52.
Partial Implementations

If a class includes an interface but does not fully implement the methods defined by
that interface, then that class must be declared as abstract.

abstract class Incomplete implements Callback


{
int a, b;
void show()
{
System.out.println(a + " " + b);
}
// ...
}
Nested interface

An interface can be declared as member of a class or another interface. Such


interface is called a member interface.

Ex: class A
{
public interface prg
{
voud disp();
}

}
Nested interface
▪ Interfaces (or classes) can have only public and default access specifiers when
declared outside any other class.

▪ This interface declared in a class can either be default, public, protected not
private.

▪ While implementing the interface, we mention the interface as c_name.i_name

▪ Here c_name is the name of the class in which it is nested and i_name is the
name of the interface itself
Nested interface

class Test
{
interface Yes
{ void show();
}
}

class Testing implements Test.Yes


{ public void show()
{ System.out.println("show method of interface");
}
}
Nested interface

class A
{
public static void main(String[] args)
{
Test.Yes obj;
Testing t = new Testing();
obj=t;
obj.show();
}
}
Applying Interfaces

// Define an integer stack interface.


interface IntStack
{
void push(int item); // store an item
int pop(); // retrieve an item
}
class FixedStack implements IntStack
{
private int stck[];
private int tos;
FixedStack(int size)
{ stck = new int[size];
tos = -1;
}
public void push(int item)
{ if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop()
{
if(tos < 0)
{ System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class IFTest
{ public static void main(String args[])
{ FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
for(int i=0; i<5; i++) mystack1.push(i);
for(int i=0; i<8; i++) mystack2.push(i);
System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}
Variables in Interfaces
We can use interfaces to import shared constants into multiple classes.

interface SharedConstants
{ int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
}
Class A implements SharedConstants
{ int x;
A() { x=1; }
void fun()
{ if (x > 1 ) return NO; else return YES; }
}
Interfaces Can Be Extended
interface A
{
void meth1();
}

interface B extends A
{
void meth2();
}
// This class must implement all of A and B
class MyClass implements B
{
public void meth1()
{ System.out.println("Implement meth1().");
}

public void meth2()


{ System.out.println("Implement meth2().");
}
}
class prg
{ public static void main(String arg[])
{ MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
}
}

Any class that implements an interface must implement all methods


defined by that interface.
Create an interface Area with following method
void findArea(int, int);

Create a two class namely Rectangle and Triagle which


implements Area interface.

Write a java program to find the area of rectangle and triangle.


interface Area
{
float findArea(int x, int y);
}

class Rectangle implements Area


{ class Triangle implements Area
public float findArea(int x, int y) {
{ public float findArea(int x, int y)
return (x*y); {
} return (0.5*x*y);
} }
}
class interfacePrg
{ public static void main(String args[])
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();
Area a;
a= r;
System.out.println("Area of rectangle ="+a.findArea(10,20));
a= t;
System.out.println("Area of triangle ="+a.findArea(5,10));
}
}
Create an interface Vehicle with 2 methods
void numberOfSeats();
void numberOfWheel();

Create a two class namely car and bike which implements


vehicle interface.

You might also like