Interfaces & Packages
October 9, 2022 1
Interfaces:
Define, implement and extend, Accessing Interface variables, Default
interface methods, Using static method in interface
Packages:
Java API Packages, Using System Packages, Creating accessing and using
a package, Importing packages, Adding a class to a Package, Hiding
classes.
October 9, 2022 2
Interfaces
• 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.
• Once it is defined, any number of classes can implement an interface.
• Also, one class can implement any number of interfaces.
Interfaces
• To implement an interface, a class must create the complete set of
methods defined by the interface.
• By providing the interface keyword, Java allows you to fully utilize the
“one interface, multiple methods” aspect of polymorphism.
ABSTRACT CLASS AND METHODS
Abstract methods are those methods which are to be redefined in sub class , thus making
overriding compulsory.
Example:
abstract class shape
{
………………….
………………….
abstract void draw(); // prototype
…………………
…………………
}
Rules
• We cannot use abstract classes to instantiate objects directly.
• The abstract method of an abstract class must be defined in its sub
class.
• We cannot declare abstract constructor or abstract methods.
INTERFACES
Multiple inheritance is not possible in java programming language but we can
achieve the feature through interfaces.
An interface is basically a kind of class.
Like class it contain method and variables with the difference that an interface
can contain only abstract method and abstract classes.
They cannot contain any code.
This is the responsibility of the class that implements an interface to define the
code for implementation of these methods.
Difference between class and interface.
CLASS INTERFACE
[Link] members of an interface are
[Link] member of a class can be always declared as constant.
constant or variables.
[Link] class definitions can contain [Link] methods in an interface are
code for each of its methods. abstract in nature.
[Link] can be instantiated by declaring [Link] cannot be used to declare objects,
objects. It can be only inherit by class.
[Link] can use various access specifiers 4. It can only use the public access
like public , private or protected. specify.
Defining an Interface
Here interface is a keyword and interface name is any valid java variable
.
Syntax:
interface interfaceName
{
Variable Declaration;
Methods Declaration;
}
Extending Interfaces
Like classes, Interfaces can also be extended. That is an interface can be sub
interfaced from other interfaces by using the keyword extends.
Syntax:
Interface name1 extends name2
{
Body of name 2
}
Implementing the interfaces
Interfaces are used as “super classes” whose properties are inherited by classes by
using the keyword implements.
Syntax:
Class classname impements interfacename
{
body of class
}
Interfaces
interface is a reserved word
None of the methods in
an interface are given
public interface Doable a definition (body)
{
public void doThis();
public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}
A semicolon immediately
follows each method header
Interfaces
■ An interface cannot be instantiated
■ Methods in an interface have public visibility by default
■ A class formally implements an interface by:
❑ stating so in the class header
❑ providing implementations for each abstract method in the interface
■ If a class asserts that it implements an interface, it must define all
methods in the interface
Interfaces
public class CanDo implements Doable
{
public void doThis ()
implements is a
{
reserved word
// whatever
}
public void doThat () Each method listed
{ in Doable is
// whatever given a definition
}
// etc.
}
Example 1:
Interface Area
{
final static float pi=3.14f;
int compute(int x, int y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
Return(x*y);
}}
Class circle implements Area
{
public float compute(float x, float y)
{
return(pi*x*x);
}
}
class test
{
public static void main(String args[])
{
Rectangle r1= new Rectangle();
circle c1= new circle();
Area a;
a=r1;
[Link](“Area of a rectangle=“+ [Link](10,20));
a=c1;
[Link](“Area of a square=“+ [Link](10,0));
}
}
Example 2:
• To implement an interface we use keyword: implements
• // Java program to demonstrate working of
• // interface.
• import [Link].*;
•
• // A simple interface
• interface In1
• {
• // public, static and final
• final int a = 10;
•
• // public and abstract
• void display();
• }
Example 2:
// A class that implements the interface.
class TestClass implements In1
{
// Implementing the capabilities of
// interface.
public void display()
{
[Link](“ABCD");
}
// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
[Link]();
[Link](a);
}
}
Program to show the multiple inheritance.
interface a // an interface is created
{
Int a=10; //variable declared
}
Interface b
{
String str =new string (“hello”);
}
Interface c extends a, b
// interface c inherit a and b interface OUTPUT
{ 10
Void show(); Hello
}
Program to show the multiple inheritance.
Class test implements c
{
Public void show()
{
System .out. Println (“value of a “+ a) ;
System .out. println (“value of string:” + str) ; } }
Class test
{
Public static void main( String args[])
{
test t1 = new test () ;
t1. show () ;
} }
Using static method in interface
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
Using static method in interface
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
[Link]();
[Link]([Link](3));
}}
Example of an Interface in Java
• interface MyInterface {
• /* compiler will treat them as:
• * public abstract void method1();
• * public abstract void method2(); */
public void method1();
public void method2();
}
Example of an Interface in Java
• class Demo implements MyInterface {
• /* This class must have to implement both the abstract methods
* else you will get compilation error */
• public void method1() {
• [Link]("implementation of method1");
• }
Example of an Interface in Java
public void method2() {
[Link]("implementation of method2");
}
public static void main(String arg[]) {
MyInterface obj = new Demo(); obj.method1();
}
}
Packages:
October 9, 2022 DEPARTMENT OF ELECTRONICS AND TELECOMMUNICATION 27
Introduction
Packages are java’s way of grouping a variety of classes and /or
interfaces together .
The grouping is done according to the functionality .
Benefits :
• The classes contained in the packages of other program can be easily
reused.
• In packages , classes can be unique compared with classes in other
packages .
• That is two classes in different package can have the same name.
Introduction
Benefits :
• Package provide a way to “hide” classes thus preventing other
programs or packages from accessing classes that are meant
for internal use only.
Java Package
A java 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.
Java API Packages
Java Application Programming Interface (API) is the area of Java development kit (JDK).
An API includes classes, interfaces, packages and also their methods, fields, and
constructors.
Understanding API in Java
October 9, 2022 DEPARTMENT OF ELECTRONICS AND TELECOMMUNICATION 31
Java API Packages
Java Development Kit (JDK) is usually made up of three fundamental components, as per below:
1. Java compiler
2. Java Virtual Machine (JVM)
3. Java Application Programming Interface (API)
October 9, 2022 DEPARTMENT OF ELECTRONICS AND TELECOMMUNICATION 32
Java API Packages
Java packages are classified in into two types:
1 java API Packages
2 User defined packages
Java API provide a large number of classes grouped into
different packages according to functionality
• [Link] (fundamental to the design of the Java programming language )
• [Link] (The basic utility classes required by the programmer are provided by this)
• [Link] (set of input streams and a set of output streams used to read and write data to files or other input and output sources.)
• [Link](Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-based applications in
Java. )
• [Link](Provides the classes for implementing networking applications.)
• [Link](Provides the classes necessary to create an applet and the classes an applet uses to communicate with
its applet context.)
The package are organized in a hierarchical structure .this means
the package named java contains the package awt , which inturn
contains various classes .
Package
Java
Package containing awt package
awt
Color Package containing classes
Graphics
Image
10/9/2022 35
Creating Packages
To create a package we must first declare the name of the
package using package keyword followed by a package name .
this must be the first statement in a java source file.
Then we define a class just as we normally define a class.
Package
• Declare the package at the beginning of a file using the form
package packagename ;
• Define the class that is to be put in the package and declare it
public.
• Create a sub directory under the directory where the main source
file are stored .
• Store the listing as the [Link] file in the subdirectory
created.
• Compile the file this create .class file in the subdirectory.
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.
Simple example of java package
//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}
Access Modifiers in Java
There are two types of modifiers in Java: access
modifiers and non-access modifiers.
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.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Understanding Java Access Modifiers
ccess Modifier within class within package outside package by outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
• Simple example of private access modifier
• In this example, we have created two classes A and Simple.
• A class contains private data member and private method.
We are accessing these private members from outside the class,
so there is a compile-time error.
Simple example of private access modifier
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the
class.
The use of private constructor is to serve singleton classes.
A singleton class is one which limits the number of objects creation to one.
Using private constructor we can ensure that no more than one object can be created at a time.
The private constructor is useful in case we want to restrict the object creation.
For example, Singleton pattern can be implemented using a private constructor.
Role of Private Constructor
public class A
{
//craeting a private constructor
private A()
{
}
void display()
{
[Link]("Private Constructor");
}
}
Role of Private Constructor
private class Test
{
public static void main(String args[])
{
//compile time error
A obj = new A();
}
}
[Link]
public class PrivateConstructorDemo
{
//creating an instance variable of the class Tester
private static PrivateConstructorDemo pcd;
//creating a private constructor
private PrivateConstructorDemo()
{
}
[Link]
//creating a static method named getInstance()
public static PrivateConstructorDemo getInstance()
{
if(pcd == null)
{
//creating a constructor of the class
pcd = new PrivateConstructorDemo();
}
return pcd;
}
[Link]
//main() method
public static void main(String args[])
{
PrivateConstructorDemo pcd = [Link]();
PrivateConstructorDemo pcd1 = [Link]();
//invokes the getInstance() method and prints the corresponding result
[Link]([Link](pcd1));
}
}
//output
//true
2) 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.
2) Default
• Example of default access modifier
• In this example, we have created two packages pack and
mypack.
• We are accessing the A class from outside its package, since A
class is not public, so it cannot be accessed from outside the
package.
Example of default access modifier
/save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
Example of default access modifier
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
3) 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 modifier.
3) Protected
• Example of protected access modifier
• In this example, we have created the two packages pack and
mypack. The A class of pack package is public, so can be
accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from
outside the class only through inheritance.
Example of protected access modifier
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Java Access Modifiers with Method Overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be
more restrictive.
class A{
protected void msg(){[Link]("Hello java");}
}
public class Simple extends A{
void msg(){[Link]("Hello java");}//[Link]
public static void main(String args[]){
Simple obj=new Simple();
[Link]();
}
}
Hiding classes:
• Hiding classes:
• When we import a package using astric(*), all public classes are imported.
• However ,we may preffer to “not import” certain classes.
• i.e, we may like to hide these classes from accessing from outside of the package.
• such classes should be declared ”not public”.
Hiding classes:
EX:
package p1;
public class X
{
Body of X
}
class Y
{
Body of Y
}
62
Thank You!!!