You are on page 1of 25

Chapter 3

Interface and Packages

MULTIPLE INHERITANCE USING INTERFACE

Class aextends b extende

is not permitted in java however the designer of java could not overlook the
importance of multiple inheritance. java provide alternative approach known as
interfaces to support the concept of multiple inheritance. a
Defining Interface
An interface is basically a kind of classes, interfaces contains methods and
variables but with a major difference is that interface defines only abstract
method and final field. This means that interfaces do not specify any code to
implement these methods and data field contains only constant. and therefore it
is responsibility of class that implements and interface to define the code for
implementation of these methods

The interface is defined much like a class. The general form is


interface interfacename

return typemethodnamel(parameterList);
return type methodname2(parameterList);

type final varl=value;


type final var2=value;

Note :-AIl variables are declared as


only list of method without anybody constants methods declaration will contain
statement.

45

Education
TecluIical
Board of
harashtrastate
class eXC

is name of the method. Keen


lame is name of the interface, method name
end with semicolon. They
n the mind the method doesn't have body and they contain some variable but
may
ae essentially abstract method. The interface final. Let us see the example of
nat variable must be constant and declared as
animal using interface
interface Animal

void description();
void travel();
} / by zero

See the above example, here the Animal is declared as interface which contain
two methods - description and travel.
Implementation Interface
Once the interface is defined one or more classes can implement it. To do this
you have to simply include implement clause in the class definition and create
the all method defined by that interface. The general syntax is as shown

class classname [extends superclass]


[implements interface[interface...]

body of the class

In above general form [] indicates


optional.

class A

void show)
System.out.println(I am in class A");

interfaceB

void display();

implements B
classC extends A
interface Bimplemented over here
display) / method of
void
System.out.println("Implementinginterface");
class D

public static void main(String args))


Cobl =new C);
obl.show);
obl.display0;
OUTPUT: re
Iam in class A
Implementing interface
See in the above example we have created one class A,
class C inherites the class A as well as implements the one interface B. The
method show) of class A is now available to interface B. So the
the interface B it has to define all the methods class
C. As class O implements
B over here have only one mnethod
declared in interface B. Interface
which is now defined by class C.
Implementation through Interface Reference
We can declare the variable as object
the class. A instance of the any class reference that use interface rather than
such a variable. When a method is that implements the interface can store in
called on one of this references the
XIV version of the method will be called based on the actual instance correct
interface being referred to of the
Let us see through example.

interface MyInterface
void show0;
class A implements Mylnterface
void show)

System.out.println("interface implemented"');
class InterfaceDemo

public static void


{ main(String args1)
MyInterface my=new A);
my.show);

Education 3
Techmical
Boardof
Maharashtrastate
OUTPUT:
interface implemented

Notice that the variable my is declared of interface type MyInterface and it


was assigned with the object of type A. It can be used to access the method
show) of Atype which is there in interface Mylnterface and implemented by
class A but it can not access the method display) of class A. Because it is not
in interface MyInterface.An interface reference variable have the knowledge
of the methods and variable declared by its interface.
D
Variables in Interface

Allvariable declared in the interface must be constant. So if any interface


contains the variable and if a class implements
T that interface
hthen aall the
i
variable will be available to the class implementing that interface.

interface MyInterface
{
final int a;
final float b;
final byte c;
final double d;
final char e;
erc
final long 1;

bo
Define interface and its need with example
Def.An interface is acollection of abstract methods and final fields. Interfaces
do not specify any code to implement these methods and data fields contain
only constants.
An interface is not a class. Writing an interface is similar to writing a class, but
they are two
different concepts. Therefore, it is the responsibility of the class that
implements an interface to define the code for implementation of these
methods.

Need of interface: Java does not support multiple inheritance. That is classes
in Java cannot have more than one super class. Java allows the use of interface
to implement multiple inheritance.Although a Java class cannot be a subclass
of more than one super class, it can implement more than one interfaces.
interface Area

final static float pi=3.14F;


float compute(float x, float y);

4
clas
class Rectangle implements Area
public float compute(float x, float y)
return(x * y);

class Circle implements Area T h a k r e

public float compute(float x, float y)


return(pi*x * x);

class InterfaceArea
{
public static void main(String args[])
Rectangle rect = new Rectangle();
Circle cir = new Circle);
Area area;
area = rect;
cise
Writ
Writ
System.out.println("Area
area = cir;
Of Rectangle ="+ area.compute(5,6);
betw
System.out.println("Area Of Circle ="+
area.compute(10,0));
c) What is interface? How do they differ from class?
Ans: Interface is known as kind of a class. So
and variables but with major interface also contains methods
difference the interface defines
method and final fields. This means that interface do not specifyonly abstract
implement those methods and data fields contains
is the responsibilityof the
any code to
only constants. Therefore, it
for implementation of theseclass that implements an interface
methods. to define the code
Sr
........
No, CLASS
1|Ithas instance variable.
INTERFACE
It has final
2
It has non abstract
method. variable.
It has by default
3
We can create object of
class. abstract method.
We can't create object of
4 Class has the access
specifiers
like public, private, and
interface.
Interface has only public access
specifiers

Tecm
Board of
Mabarasbtrastate
)

class exC

5 The memory is allocated We are not allocating the memory for th


for the classes.
interfaces.

d) Write a program to make following


inheritance:
Interface: Gross Class: Employee
TA, DA, Name, re
rOSS_salO) basic sal ()

Class: Salary
disp_ sal ()
HRA

XIV. Exercise(
Write interface Gross
2 Write
betw
double TA=800.0:
double DA=3500;
void gross_sal);
}
class Employee
{

String name;
double basic sal;
Employee(String n,double b)
nameFn;
basicsal=b;
void display()

System.out.println("'Name of Employee :"+name);


System.out.println("Basic Salary of Employee :"+basic sal):
class Salary extends Employee
(double HRA; implements Gross
Salary(String n, double b, double h)

6
cla

{ super(n,b);
HRA=h;

void disp_sal)
{ display);
System.out.println("HRA of Employee :"+HRA);
public void gross_ sal) h a k r

+ DA + HRA;
double gross sal=basic sal + TA Employee :"+gross_sal);
System.out.println("Gross salary of

class interfacel1
main(String args[])
{public static void
Salary("Sachin",8000,3000);
{ Salary s=new
s.disp_sal0; SSA
S.gross sal);
Bo

cise (T
OUTPUT:-
Write t Name of Employee :Sachin
Vrite a Basic Salary of Employee :8000.0
etwect HRA of Employee :3000.0
:15300.0*/
Gross salary of Employee
multiple inheritance with
example howv to achieve
E) Explain with the interface -2 M, example - 2M)
interface.(Multiple inheritance - 2 M,
inheritance where a derived class may
Multiple inheritances: It is a type ofnot possible in case of java as you cannot
It is
have more than oneparent class. level and one
instead there can be one classsimilar to
have two classes at the parent multiple interface. Interface is
interface at parent level to achieve and abstract method.
Interfaces can
variables
classes but can contain on final
be implemented to a derived
class.
Class: test
Interface: Sports
Rollno, Name, ml,m2
sport _wt-5
disp)

Class: result

disp( )which display all


details of student along with
total including sDort wt
Board ofTec
arashtrastate
interface sports
int sport wt=5;
void disp0; a k r e

class test

int roll no;


String name;
int ml,m2;

test(int r, String nm, int ml1,int m12)


evclopnent us { roll no=r;
name=nm:
ml=mll;
m2=m12;

class interfaceresult extends test implements sports


interfaceresult(int r, String nm, int ml1,int m12)
{
super(r,nm,ml 1,m12);
public void disp)
System.out, println("Roll no : "+roll_no);

S
System.out.println("Name :"+name);
System.out.println("subl :"+ml);
System.out.println("'sub2: "+m2):
System.out.println("sport_wt:"+sport_wt);
int (=ml+tm2+sport_wt;
System.out.println("total : "+);
public static void main(String args)
interfaceresult r= new interfaceresult(101,"abc",75,75);
r.disp);

CAjdk1.2.2\bin>javac interfaceresult.java
CAjdkl.2.2\bin>java interfaceresult
Roll no : 101
Name : abc
subl:75
sub2:75
sport wt:5
total: 155

15

ofTechical Education
aharashira state Board
PACKAGES
the code
We have repeatedly stated that the main features of oops is its ability to reuse
already created .this is limited to reusing the classes within a program. if we need to use
classes from other programs without physically copying them into the program under
development. This can be accomplished in java by using packages kre

java packages are classified into two groups


" java API PackagesOR Built in packages
user defined packages
List any 4 built in packages from Java APl along with their use.
Ans:
1. java.lang - language support classes. These are classes that java compiler itself
uses and therefore they are automatically imported. They include classes for
primitive types, strings, math functions, threads and exceptions.
2. java.util - language utility classes such as vectors, hash tables, random numbers,
date etc.
3.output
java.io - input/output support classes. They provide facilities for the input and
of data
. Exerc
1. W 4. java.awt - set of classes for implementing graphical user interface. They include
2. W classes for windows, buttons, lists, menus and so on.
be
5. java.net - classes for networking. They include classes for
local computers as well as with internet servers. communicating with
6. java.applet classes for creating and implementing applets.
Suy

45

Technical Education
Mabarashtra state Board of
State how to create user defined package and
accessed in Java.OR
Ans: To create a package is gquite easy: simply include a
package
classes declared within command
the first statement in a Java source file. Any as
belong to the specified package. The package that file will
which classes are stored. If youomit the statement defines a name space in
put into the default package, which haspackage statement, the class names are
no name. Java is uses file system
directories to store packages. This directory name must match with the package
GUT4
name exactly. N'akr
Syntax:

package pkg;/it wvillereate package pkg


Here, pkg is the name of the package.
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:

Example:
import pkgl[.pkg2].(classname *)
e.g. import pkg;// we can access this
package in another source file
Example:
package MyPack;
public class Balance

String name;
double bal;
public Balance(String n, double b)

name =n;

10

Maharahtra sute IBoard of Iechical Fcatinn


bal = b;
Thakre

public void show)

if(bal<0)
System.out.print("--> ");
System.out.println(name + ": S" + bal);

import MyPack.Balance;

class TestBalance

public static void main(


String args[])

(Tei
199.88):
e the
eap Balance test new Balance("ABCDE",
cen
show)
test.show); //you may also call

package? explain with


declare and access(import)
What ispackage? how to
example
partitioning the class namespace into
Java provides a mechanism formechanism is the package The package
more manageable parts. This controlled mechanism. Package can be
is both naming and visibility the first statement in java source code.
created by including package as
that file will belong to the specified
Any classes declared withinnamespace
package. Package defines a in which classes are stored.
a package is:
The syntax for defining/declare
11

Education
of Technical
atra state Board
package package name;

eg
package mypack;
system directories
directories. Java uses file
Packages are mirrored by files of any classes which are declared in Jy
The class name as
to store packages. stored in a directory which has same
a package must be package name
name. The directory must match with the package name and
package createdby separating
T h a k

exactly. A hierarchy can be period(.) as packl.pack2.pack3; which


sub package name by a packl\pack2\pack3.
requires a directory structure as
Example

package package1;
public class Box
{
int l=5;
int b=7;
int h = 8;
public void display()
System.out.println("Volume is:"+(1*b*h);

source file:
import package 1.Box;
class volume

public staticvoid main(String a])


Box b=new Box0;
b.displayO:

/*OUTPUT:
C:ljava programsl>java volume
Volume is:280
*

12

ard of Techical
acc
Interface: Transaction
Class: Account
Package deposit)
Acc no, Bal
Package Trans dis)
Thakre

Class: Saving
amt
displav)

package acc;
public class account

public int acc no;


public int bal;
account(int a,int b)

acc noFa;
bal=b;
}
public void dis()
System.out.println("accno"+acc no);
System.out.println("balance"tacc no);

package trans;
public interface transaction TY
{ orEas
void deposit(); Since

import acc.account;
import trans.transaction;
transaction
public class saving extends account implements
{int amt=5000;
int total;
saving(int a,int b)
13
super(a,b);:

public void deposit()


T n
T ah a k r e

Applica
total=bal+amt;

public void display()


{(System.out.println("total amount"+total);
System.out.println("acc no"+acc no);
public static void main( String ar[])
saving s = new saving(1 1,7000);
s.dis();
s.deposit();
s.display):
tua
ogram
to 500
package useful;
public class useme

public int total;


public void area(int a)

System.out.println("area is"+(a*a);
public void salary()
Books

int ta-200,da=3000,hra=5000;
total-tatdathra;
System.out.println("total salary="ttotal);

import useful.useme;
class pack suw
public static void main(String ar[])
Lducation 14
useme uFnew useme);
U.area(3);
u.salary():
}
protected in
specifiers public, private and
Write the effect of access marks)
(Each specifier 2
package. while using packages and
Visibility restriction must be considered are imposed by various access
restrictions
inheritance in program visibility as container for classes and other
protection modifiers. packages acts for data and methods.
container
package and classes acts as
declared with the access protection
Data members and methods can be
public. Following table shows the
modifiers such as private, protected and J
access protections

Friendly Private private


Access modifier public protected
protecte
(default)
(Teacher mu
ethe situations
a program us Access location
n l to yes
500(153 Same class yes yes yes yes

no
yes yes
Subclass in yes yes
same

package no no
Other classes in yes yes yes

same package
no
Subclass in yes yes no yes
other
packages no
Non-subclasses in no no no
yes
bks
other
packages

15

atso
useme uFnew useme();
u.area(3);
u.salary();

GUI Applica
protected in
Write the effect of access specifiers public, private and
package. (Each specifier 2 marks)
Visibility restriction must be considered while using packages and
inheritance in program visibility restrictions are imposed by various access
protection modifjers. packages acts as container for classes and other
package and classes acts as container for data and methods.
Data members and màthods can be declared with the access protection
modifiers such as private, protected and public. Following table shows the
access protections

Access modifier public Drotected Friendly Private private


protecte
(default)
Access
location
Same class yes yes yes yes yes
Subclass in yes yes yes yes no
same

package
Otherclasses in yes yes Yes no no
same package

Subclass in yes yes no


other yes no

packages
Non-subclasses in yes no no no no
other
packages

15
ourd of
Tectaical Educa
class eXC

main(String ar[])
public static void

lication Develo

int z=1/0;
System.out.print/n("z"+z);
System.out.println("hello");

C\Users\Admin\ Desktop\jdk1.8.0_181\bin>java exc


java.lang.ArithmeticException: / by zero
Exception in thread "main"
at exc.main(exc.java:5)
ercise (Tea class exc
Write the
Write a pi
between 1 {public static void main(String ar[])
try

int z=1/0;

System.out.printin ("z"+z);

catch(Exception e)

System.out.println("hello");

pard of Tech
extends Exception
dass myexception

myexception(String msg)

super(msg);

class exception1

ar[)
{public static void main(String

double x=5.0,y=1000.00;

try

{
double z=x/y;

if(z<0.01)
{
myexception("number is too small");:
throw new

)
catch(myexception e)

System.out.printin(e);
System.out.printin(e.getMessage();System.out.printin("caught exception");
e
Board of Techni )

finally

System.out.printin("i am always here");


pplication Devel

))

Output
C\Users\Admin\Desktop\jdk1.8.0_181\bin>java exception1

myexception: number is too small

number is too small

caught exception

iam always here

WAP to input name and salary of


if entered salary is negative
employee and throw user defined exception :
import java.util.*;

class myexception extends Exception

myexception(String msg)

super(msg);

) T)
tasy
198

class exception2
(public static void main(String ar[)

Scanner sc=new Scanner(System.in);


Board o
System.out.println ("enter name");
String name=sc.nextLine();
System.out.printin("enter salary");

int sal=sc.nextint();
GUI Application Developnent

try

if(sal<o)

negative");
throw new myexception("'salary is

catch(myexception e)

System.out.printIn(e);
System.out.printin(e.getMessage());System.out.println("caught exception");

finally

System.out.printin ("i am always here");

T
19
Output
C\Users\Admin\Desktop\jdk1.8.0_181\bin>javac exception2.java

CAUsers\Admin\Desktop\jdk1.8.0_181\bin>java exception2

enter name

SS

enter salary
888
GUI
Application Developnent using VB. Net

iam always here

PASSWORD
EXCEPTION" THAT IS THROWN WHEN THE
DEFINE EXCEPTIONCALLED'NO MATCH
WRITE THE PROGRAM
ACCEPTED IS NOT EQUAL TO "MSBTE"

import java.util.*
Exception
class myexception extends

{
myexception(String msg)

super(msg);

class exception3

{public static void main(String arl])

Scanner sc=new Scanner(System.in); AT


r Easy
System.out.println("enterpassword"); nce 19

String name=sc.nextLine():

try

if(name.equals("MSBTE")

throw new myexception(" password matching");

else
GUI Applic

exception");
throw new myexception("no match

catch(myexception e)

System.out.printin(e);
System.out.printin(e.getMessage());System.out.printin(" caught exception";

finally

System.out.printin ("iam always here");

C:\UsersAdmin\Desktop\jdk1.8.0_181\bin>javac exception3.java

kl.8.0_181\bin>java exception3
C:\Users\Admin\ Desktop\jd
enter password

thakur
exception
myexception: no match
no match exception
Educ caught exception

iam always here


GUI App

class eXC

public static void main(String ar[])

int z=1/0;
System.out.printin("z"+z);
System.out.printin("hello");

C\Users\Admin\Desktop\jdk1.8.0_181\bin>java exC
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exc.main(exc.java:5)

class exc

{public static void main(String ar[])


{ try

int z=1/0;

System.out.printIn ("z"+z);
Books

catch(Exception e)

System.out.println("hello");
even extends Exception
ss

even(String s)
{super(s);

class exce

{public static void main(String ar[])


{int num=8;
try

if(num%2=-0)
throw neweven("no is even");
else

throw new even('"'no is odd");

catch(even e)
{System.out.printin(e.getMessage();
System.out.printIn(e);

System.out.printIn("hello");

}C:Users\Admin\Desktop\jd k1.8.0_181\bin>java exce


no is even

even: no is even

hello
las eoee
Psrm )
psumc)
twy

SpcaHeo'')
3 Sop(Hello'")
denatly
sap(
cateh l EKcekton e)
uTam alyay hu),
Inty= lols
sopl e;
Sop ( ey-) +)

9 am

certin un Thuad maun ova.danq:


Auth mthcGycegtin / by eno. at
Oyee- main( ee 'Jawa g)

You might also like