Unit 3
Unit 3
An interface in java is a blueprint of a class. It has static constants and abstract methods.
There are mainly three reasons to use interface. They are given below.
Interface is declared by using interface keyword. It provides total abstraction; means all the methods in
interface are declared with empty body and are public and all fields are public, static and final by default. A
class that implement interface must implement all the methods declared in the interface.
Syntax:
interface interface_name
{
variable declaration; // declare constant fields
methods declaration; // declare methods that abstract ;
}
Here interface is a keyword and interface_name is any valid java variable (just like class name)
Note all variables are declared as constant, Method declaration will contain only a list of methods
without any boby content.
interface Student
void display();
}
Another example
interface Area
void show();
In this example, Printable interface has only one method, its implementation is provided in the A class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Output:
Hello
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();
}}
Output:
drawing circle
File: TestInterface2.java
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Output:
ROI: 9.15
Q) Multiple inheritance is not supported through class in java but it is possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class
because of ambiguity. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
Hello
What is interface? How it is different from class? With suitable program explain the use of interface.
(2M – what is interface, 3M – 3 points of differences between interface and class, 3M – example)
Interface: Java does not support multiple inheritances with only classes. Java provides an alternate approach
known as interface to support concept of multiple inheritance. An interface is similar to class which can
define only abstract methods and final variables. Difference between Interface and class
CLASS INTERFACE
Should contain only concrete methods (methods Should contain only abstract methods
with body) (methods without body)
Methods can be final and static Methods should not be final and static
D:\>java result
Roll no : 101
Name : abc
sub1 : 75
sub2 : 75
sport_wt : 5
total : 155
Extending Interfaces
One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting
classes.
It must provide implementation of all methods defined within the interface inheritance.
Note : Any class that implements an interface must implement all methods defined by that interface,
including any that inherited from other interfaces.
Body of name2;
Example:
Interface code
Void display();
Example:
Interface code
Interface itemcode
Void display();
………………………
}
Example:
interface if1
void dispi1();
void dispi2();
}
}
c1obj.dispi1();
c1obj.dispi2();
}
Output :
This is display of i1
This is display of i2
Note : We have to define disp1() and disp2() in cls1.
Implementing Interfaces
Interfaces are used as “superclasses” whose properties are inherited by classes.
interface area
{
double pi = 3.14;
double calc(double x,double y);
}
class test7
{
public static void main(String arg[])
{
rect r = new rect();
cir c = new cir();
area a;
a = r;
System.out.println("\nArea of Rectangle is : " +a.calc(10,20));
a = c;
System.out.println("\nArea of Circle is : " +a.calc(15,15));
}
}
Accessing Interface Variables
Output:Hello
Welcome
o Nested interface must be public if it is declared inside the interface but it can have any access modifier if
declared within the class.
o Nested interfaces are declared static implicitely.
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){System.out.println("Hello nested interface");}
class A{
interface Message{
void msg();
}
}
interface Exam {
void Percent_cal();
}
class Student {
String name;
int roll_no, Marks1, Marks2;
Student(String n, int rn, int m1, int m2) {
name = n;
roll_no = rn;
Marks1 = m1;
Marks2 = m2;
}
void show() {
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
Java-API Packages
Java APl(Application Program Interface) provides a large numbers of classes grouped into different packages
according to functionality. Most of the time we use the packages available with the the Java API. Following
figure shows the system packages that are frequently used in the programs.
State any four system packages along with their use.
java.lang Language support classes. They include classes for primitive types, string, math
functions, thread and exceptions.
java.util Language utility classes such as vectors, hash tables, random numbers, data, etc.
java.io Input/output support classes. They provide facilities for the input and output of data.
java.net Classes for networking. They include classes for communicating with local computers as
well as with internet servers.
java.awt Set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.
Naming Conventions
Packages begin with lowercase letters. This makes it easy for users to distinguish package names from class
names. All class name begin with uppercase letter.
double y = java.lang.Math.sqrt(x);
Class name
As mentioned in the beginning of this guide that we have two types of packages in java.
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages.
Creating Packages
Declare the name of the package using the package keyword followed by package name.
1. First create a folder with the same name of package in any where
Lets assume it will create in D:\acedemic – JAVA with the name firstpackage
2. Type a program
3. Save the program in package firstpackage with the name FirstClass.java
6. To run a program
java firstpackage.FirstClass
How to access 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.
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.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Compile: A.java
Javac pack/A.java
Compile: B.java
Javac mypack/B.java
Run:
Java mypack.B
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
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();
}
}
Output:Hello
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date
class.
//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();
}
}
Output:Hello
1. Java provides a mechanism for partitioning the class namespace into more manageable parts called
package (i.e package are container for a classes).
2. The package is both naming and visibility controlled mechanism.
3. Package can be created by including package as the first statement in java source code.
4. Any classes declared within that file will belong to the specified package.
package pkg;
eg : package mypack;
Packages are mirrored by directories. Java uses file system directories to store packages. The class files of any
classes which are declared in a package must be stored in a directory which has same name as package name.
The directory must match with the package name exactly.
Syntax: To access package In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions.
Example:
package1:
package package1;
public class Box {
int l= 5;
int b = 7;
int h = 8;
public void display()
{ System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;
class VolumeDemo {
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}
OR
package mypack;
public interface test {
public int x=5;
public abstract void display();
}
B) Importing package inside another java code
import mypack.test;
class test1 implements test
{
public void display()
{
System.out.println("x from interface :"+x);
}
public static void main(String args[])
{
test1 t1 = new test1();
t1.display();
}
}