0% found this document useful (0 votes)
35 views24 pages

Unit 3

The document discusses interfaces in Java. It defines what interfaces are, how they are declared and implemented by classes, how they allow multiple inheritance, and provides examples of interface usage.

Uploaded by

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

Unit 3

The document discusses interfaces in Java. It defines what interfaces are, how they are declared and implemented by classes, how they allow multiple inheritance, and provides examples of interface usage.

Uploaded by

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

Interface in Java

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.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare interface?

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)

Variable are declared as follows:

static final type variablename = value;

 Note all variables are declared as constant, Method declaration will contain only a list of methods
without any boby content.

return-type methodName1 (parameter_list);

interface Student

static final int code=1001;

static final String name =”ABC”;

void display();

}
Another example

interface Area

static final float pi=3.14;

float compute(float x, float y);

void show();

Java Interface Example

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");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

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();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Output:

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

Supports only multilevel and hierarchical Supports all types of inheritance –


inheritances but not multiple inheritance multilevel, hierarchical and multiple

"implements" keyword should be used to


"extends" keyword should be used to inherit inherit

Should contain only concrete methods (methods Should contain only abstract methods
with body) (methods without body)

The methods can be of any access specifier (all


the four types) The access specifier must be public only

Methods can be final and static Methods should not be final and static

Variables can be private Variables should be public only

Can have constructors Cannot have constructors


Cannot have main() method as main() is a
Can have main() method concrete method
Output :

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.

When a class implements an interface that inherits another interface,

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.

interface name2 extends name1


{

Body of name2;

Example:

Interface code

Int code =1001;

String name = “ABC”;

Interface itemcode extends code

Void display();

Example:

Interface code

Int code =1001;

String name = “ABC”;

Interface itemcode

Void display();

Interface item extends code, itemcode

………………………

}
Example:

interface if1

void dispi1();

interface if2 extends if1

void dispi2();

class cls1 implements if2

public void dispi1()

System.out.println("This is display of i1");

public void dispi2()

System.out.println("This is display of i2");

}
}

public class Ext_iface

public static void main(String args[])


{
cls1 c1obj = new cls1();

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.

class class_name implements interface_name


{
Body of class;
}
Genral Form:-
class class_name extends superclass
implements interface_name1, interface_name2
{
Body of class;
}
Various forms of interface implementation
Write a java program to calculate area of circle in which implementation of interfaces as class type.

interface area
{
double pi = 3.14;
double calc(double x,double y);
}

class rect implements area


{
public double calc(double x,double y)
{
return(x*y);
}
}

class cir implements area


{
public double calc(double x,double y)
{
return(pi*x*x);
}
}

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

Implementing Multiple inheritance using interface


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();
}
}

Output:Hello
Welcome

Java Nested Interface


An interface i.e. 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


There are given some points that should be remembered by the java programmer.

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.

Syntax of nested interface which is declared within the interface


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
In this example, we are going to learn how to declare the nested interface and how we can access
it.

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();
}
}

Example of nested interface which is declared within the class


Let's see how can we define an interface inside the class and how can we access
it.

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


class student //program in java to show multiple inheritance
{
int rollNumber;
void getNumber(int n)
{
rollNumber=n;
}
void printNumber()
{
System.out.println("RollNo is " +rollNumber);
}
}

class test extends student


{
float part1,part2;
void getMarks(float a, float b)
{
part1=a;
part2=b;
}
void putMarks()
{
System.out.println("Marks Part1 "+part1);
System.out.println("Marks Part2 "+part2);
}
}
interface sports
{
float sportwt=6.0F;
void putwt();
}
class results extends test implements sports
{
float total;
public void putwt()
{
System.out.println("Sports Marks "+ sportwt);
}
void display()
{
total=part1+part2+sportwt;
System.out.println("Total marks of " +rollNumber+" is "+total);
}
}
class mainClass
{
public static void main(String srgs[])
{
results a=new results();
a.getNumber(10);
a.printNumber();
a.getMarks(10.0F,25.5F);
a.putMarks();
a.putwt();
a.display();
}
}

/* Program to implement the Multiple Inheritance */

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() {

System.out.println("Student Name : "+name);


System.out.println("Roll no : "+roll_no);
System.out.println("Marks1 : "+Marks1);
System.out.println("Marks2 : "+Marks2);
}
}

class Result extends Student implements Exam {


float per;
Result(String n,int rn,int m1,int m2) {
super(n,rn,m1,m2);
}

public void Percent_cal() {


int tot = Marks1 + Marks2;
per = (float)tot / 2;
}
void display() {
show();
System.out.println("Percentage = "+per);
}
}
public class StudentDetails {

public static void main (String[] args) {

Result r = new Result("Aashish",11,75,95);


r.Percent_cal();
r.display();
}
}
Output
C:\>javac StudentDetails.java
C:\>java StudentDetails
Student Name : Aashish
Roll no : 11
Marks1 : 75
Marks2 : 95
Percentage = 85.
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.

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.

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 System Packages and Their Classes

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.applet Classes for creating and implementing applets.

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);

Package Name Method name

Class name

Types of packages in Java

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.

package firstpackage; //package declaration

public class FirstClass //class defination


{

This program is saved as FirstClass.java and located in directory named firstpackage.


When the source file is compiled, java will create a .class file and store it in the same
directory.
.class file must be located in a directory that has the same name as the 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

4. Go to the path where package is stored


5. Now to compile a program
javac firstpackage/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.

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
package mypack;
import pack.*;

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.

Example of package by import package.classname


//save by A.java

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

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{
public void msg(){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();
}
}
Output:Hello

What is package? How to create package? Explain with suitable example

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.

The syntax for creating package is:

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.

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

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();
}
}

What is interface? How to add interfaces to packages.


Interface:
1) It is similar to class but mainly used to define abstraction in Java
2) It contains all abstract methods and final variables inside it.
3) Interfaces have to be implemented by a class.
4) It is mainly used to achieve multiple inheritance in Java.

To add interface to packages:


1) Begin the program with „package < package name>;
2) Declare public interface
3) Declare final variables and abstract methods required.
4) Save and compile the file.
5) Create a folder with exactly same name as package name.
6) Copy class of package inside this folder.
7) Create java source code which requires interface from package
8) Import the created package inside it and use.

OR

A) Creation of package containing interface

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();
}
}

You might also like