Вы находитесь на странице: 1из 36

PACKAGE AND INTERFACE

1.Package, access control mechanism


2.Interface
3.Dynamic Method look up
Package
A package is a group of similar types of classes, interfaces and sub-packages.
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
Ø Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Ø Java package provides access protection.
Ø Java package removes naming collision.
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
How to run java package program
You need to use fully qualified name
e.g. mypack.Simple etc to run the class.
To compile and run above program we write
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:
Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
Ø import package.*;
Ø import package.classname;
Ø fully qualified name.
1) 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.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}}
//save by B.java Output:
package mypack; Hello
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}}
2) 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 Hello
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}}
3) 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.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{ OUTPUT:
public void msg(){ Hello
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();
2.Access control mechanism

Modifier Private No Protected Public


Modifier

Same class Y Y Y Y

Same package
N Y Y Y
subclass

Same package
non- subclass N Y N Y

Different Package
N N Y Y
subclass
Different Package
N N N Y
non-subclass
Subpackage in java
Ø Package inside the package is called the subpackage. It should be created to categorize the
package further.

Ø For example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc.

Ø These classes represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on.

Ø So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and
put the Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.
Package pack.java;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile:
javac -d . Simple.java
To Run:
java pack.java.Simple
Output:
Hello subpackage
Rule: There can be only one public class in a java source file and it must be saved by the public
class name.
//save as C.java otherwise Compilte Time Error
class A{}
class B{}
public class C{}
How to put two public classes in a package?
If you want to put two public classes in a package, have two java source files containing one public
class, but keep the package name same.
Example:
//save as A.java
package DEMO;
public class A{}
//save as B.java
package DEMO;
public class B{}
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static member of a
class directly. There is no need to qualify it by the class name.
Advantage of static import:
Less coding is required if you have access any static member of a class often.
Disadvantage of static import:
If you overuse the static import feature, it makes the program unreadable and unmaintainable.
Example:
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}
Output:
Hello
Java
What is the difference between import and static import?
The import allows the java programmer to access classes of a package without package
qualification whereas the static import feature allows to access the static members of a
classwithout the class qualification. The import provides accessibility to classes and interface
whereas static import provides accessibility to static members of the class.
2.Interface
Ø An interface in java is a blueprint of a class.
Ø It has static constants and abstract methods only.
Ø The interface in java is a mechanism to achieve fully abstraction.
Ø There can be only abstract methods in the java interface not method body. It is used to
achieve fully abstraction and multiple inheritance in Java.
Ø Java Interface also represents IS-A relationship.
Ø It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface.
1) It is used to achieve fully abstraction.
2) By interface, we can support the functionality of multiple inheritance.
Note:The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods are
public and abstract.
Understanding 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
Example:
In this example, Printable interface have only one method, its implementation is provided in the
Demo class.
interface printable{
void print();
}
class Demo implements printable{
public void print(){
System.out.println("Hello"); }
public static void main(String args[]){
Demo obj = new Demo();
obj.print();
}
}
output: Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.print("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
output:
Hello Welcome
Q) Multiple inheritance is not supported through class in java but it is possible by interface, why?
As explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in
case of interface because there is no ambiguity as implementation is provided by the implementation class.
Example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class testinterface1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
testinterface1 obj = new testinterface1();
obj.print();
}
}Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but its implementation
is provided by class testinterface1, so there is no ambiguity.
Interface with inheritance:
A class implements interface but one interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}output: Hello Welcome
Q) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.
//How Serializable interface is written?
public interface Serializable{
}
Nested Interface in Java
An interface can have another interface i.e. known as nested interface.
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
Nested Interface
An interface which is declared within another interface or class is known as nested interface.
The nested interfaces are used to group related interfaces so that they can be easy to maintain.
The nested interface must be referred by the outer interface or class. It can't be accessed
directly.
Points to remember for nested interfaces
Ø Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
Ø Nested interfaces are declared static implicitly.
Syntax :
interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}
Example of nested interface which is declared within the interface
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();
}
}
output:
hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer interface Showable because it
cannot be accessed directly. It is just like almirah inside the room, we cannot access the almirah directly because we
must enter the room first. In collection framework, sun microsystem has provided a nested interface Entry. Entry is the
subinterface of Map i.e. accessed by Map.Entry.
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
public static interface Showable$Message
{
public abstract void msg();
}
Example of nested interface which is declared within the class
class A{
interface Message{
void msg();
}
}
class TestNestedInterface2 implements A.Message{
public void msg(){
System.out.println("Hello nested interface");}
public static void main(String args[]){
A.Message message=new TestNestedInterface2();//upcasting here
message.msg();
}
}
Output:
hello nested interface
Can we define a class inside the interface ?
Yes, If we define a class inside the interface, java compiler creates a static nested class.
Syntax:
interface M{
class A{}
}
3.Dynamic Method Lookup
Which object a reference will actually denote during runtime, cannot always be determined at
compile time. Polymorphism allows a reference to denote objects of different types at different
times during execution. A supertype reference exhibits polymorphic behavior, since it can denote
objects of its subtypes.

When a non-private instance method is invoked on an object, the method definition actually
executed is determined both by the type of the object at runtime and the method signature.

Dynamic method lookup is the process of determining which method definition a method
signature denotes during runtime, based on the type of the object. However, a call to a private
instance method is not polymorphic. Such a call can only occur within the class, and gets bound
to the private method implementation at compile time.
The inheritance hierarchy depicted in Figure1 in the next slide has the method draw() which is
overridden in all subclasses of the class Shape.
The invocation of the draw() method in the two loops at (3) and (4) in program(given after 1
slide), relies on the polymorphic behavior of references and dynamic method lookup.
The array shapes holds Shape references denoting a Circle, a Rectangle and a Square, as shown
at (1).
At runtime, dynamic lookup determines the draw() implementation to execute, based on the type
of the object denoted by each element in the array.
This is also the case for the elements of the array drawables at (2), which holds IDrawable
references that can be assigned any object of a class that implements the IDrawable interface.
The first loop will still work without any change if objects of new subclasses of the class Shape
are added to the array shapes. If they did not override the draw() method, then an inherited
version of the method would be executed. This polymorphic behavior applies to the array
drawables, where the subtype objects are guaranteed to have implemented the IDrawable interface
Advantage:
Polymorphism and dynamic method lookup form a powerful programming paradigm that
simplifies client definitions, encourages object decoupling, and supports dynamically changing
relationships between objects at runtime..
Figure 1.Polymorphic Methods
Example:1
interface IDrawable {
void draw();
}
class Shape implements IDrawable {
public void draw() { System.out.println("Drawing a Shape."); }
}
class Circle extends Shape {
public void draw() { System.out.println("Drawing a Circle."); }
}
class Rectangle extends Shape {
public void draw() { System.out.println("Drawing a Rectangle."); }
}
class Square extends Rectangle {
public void draw() { System.out.println("Drawing a Square."); }
}
class Map implements IDrawable {
public void draw() { System.out.println("Drawing a Map."); }
public class PolymorphRefs {
public static void main(String[] args) {
Shape[] shapes = {new Circle(), new Rectangle(), new Square()}; // (1)
IDrawable[] drawables = {new Shape(), new Rectangle(), new Map()};// (2)

System.out.println("Draw shapes:");
for (int i = 0; i < shapes.length; i++) // (3)
shapes[i].draw();

System.out.println("Draw drawables:");
for (int i = 0; i < drawables.length; i++) // (4)
drawables[i].draw();
}
}

Output :
Draw shapes:
Drawing a Circle.
Drawing a Rectangle.
Drawing a Square.
Draw drawables:
Drawing a Shape.
Drawing a Rectangle.
Drawing a Map.

Вам также может понравиться