Vous êtes sur la page 1sur 8

Q1- Inner class in Java language (defnition and purpose)

Defnition
An inner class is a class that is declared within another class:
public class SimpleCalc {
private class OperatorAction{
}
}
Purpose
1. t is a wa! o" lo#icall! #roupin# classes that are onl! used in one place:
" a class is use"ul to onl! one other class$ then it is lo#ical to embed it in
that class and %eep the two to#ether.
&estin# such 'helper classes' ma%es their pac%a#e more streamlined.
(. t increases encapsulation: Consider two top)level classes$ A and *$
where * needs access to members o" A that would otherwise be declared
private.
*! hidin# class * within class A$ A+s members can be declared private and
* can access them. n addition$ * itsel" can be hidden "rom the outside
world.
,. t can lead to more readable and maintainable code: &estin# small
classes within top)level classes places the code closer to where it is used.
Q2- static and non-static methods (describe each)
1- points about static %e!word in .ava
n this section we will see some important properties o" static variable$
static method and static class in .ava. /e will also some .ava codin# best
practices related to static variables in .ava.
10 static %e!word can be applied with variable$ method or nested class.
static %e!word can not be applied on top level class. 1a%in# a top level
class static in .ava will result in compile time error.
(0 static variables are associated with class instead o" ob2ect.
,0 static variables in 2ava %eeps same value "or ever! sin#le ob2ect.
30 !ou can not use non-static variable inside a static method $ it will
result in compilation error as shown below. See /h! static variable can
not be called "rom static method "or more details.
public class TradingSystem {
Strin# description 4 'electronic tradin# s!stem'5

public static void main6Strin#78 ar#s0 {
description 4 'commodit! tradin# s!stem'5
}
}
annot ma!e a static re"erence to the non-static feld description
at 9radin#S!stem.main69radin#S!stem.2ava::0
;0 Static variables are bonded usin# static bindin# at compile time so the!
are comparativel! "aster than there non)static counter part which were
bonded durin# runtime.
<0 Static felds are initiali=ed at the time o" class loadin# in .ava$ opposite
to instance variable which is initialised when !ou create instance o" a
particular class.
>0 Static %e!word can also be used to create static bloc! in Java which
holds piece o" code to e?ecuted when class is loaded in .ava. 9his is also
%nown as static initiali=e bloc% as shown in below e?ample.
static {
Strin# cate#or! 4 'electronic tradin# s!stem'5
S!stem.out.println6'e?ample o" static bloc% in 2ava'05
}
*eware that i" !our static initiali=e bloc% throws @?ception than !ou ma!
#et 2ava.lan#.&oClassDe"Aound@rror when !ou tr! to access the class
which "ailed to load.
:0 Static method can not be overridden in Java as the! belon# to
class and not to ob2ect. so i" !ou have same static method in subclass
and super class $ method will be invo%ed based on declared t!pe o" ob2ect
instead o" runtime "or e?ample. Can we override static method in .ava is
also a popular .ava Buestion as%ed in interviews.
public class TradingSystem {
public static void main6Strin#78 ar#s0 {
9radin#S!stem s!stem 4 new Direct1ar%etAccess605
Direct1ar%etAccess dma 4 new Direct1ar%etAccess605

CC static method o" nstrument class will be called$
CC even thou#h ob2ect is o" sub)class Direct1ar%etAccess
s!stem.printCate#or!605

CCstatic method o" @Buit!nstrument class will be called
dma.printCate#or!605
}

public static void printCate#or!60{
S!stem.out.println6'inside super class static method'05
}
}

class Direct1ar%etAccess e?tends 9radin#S!stem{
public static void printCate#or!60{
S!stem.out.println6'inside sub class static method'05
}
}
Output:
inside super class static method
inside sub class static method
9his shows that static method can not be overridden in .ava and concept
o" method overloadin# doesn+t appl! to static methods. nstead declarin#
same static method on Child class is %nown as method hiding in Java.
D. " !ou tr! to override a static method with a non)static method in sub
class !ou will #et compilation error.
1-. *e care"ul while usin# static %e!word in multi)threadin# or concurrent
pro#rammin# because most o" the issue arise o" concurrentl! modi"!in# a
static variable b! diEerent threads resultin# in wor%in# with stale or
incorrect value i" not properl! s!nchroni=ed. most common issue is race
condition which occurs due to poor s!nchroni=ation or no s!nchroni=ation
o" static variable.
#i$erence bet%een static and no static
10 thin% frst and "oremost diEerence between them is that !ou can call
static method without creatin# an! ob2ect e.#. Collections.sort60. 9his
ma%es static method use"ul utilit!$ while !ou need to instantiate an ob2ect
to call non static method in .ava. Static methods are also prett! use"ul on
several desi#n pattern includin# Aactor! and Sin#leton.
(0 Fou can not access a non static variable inside an! static method in
.ava$ but reverse is fne i.e. !ou can access static variables or call static
method "rom a non static method without an! compile time error.
,0 One more worth notin# diEerence between static and non static
method is that !ou can not override static method in .ava. 9he! are
bonded durin# compile time usin# static bindin#. 9hou#h !ou can create a
similar static method in sub class$ that is %now as method hidin# in .ava.
30 static methods are %nown as class methods$ i" !ou s!nchroni=e static
method in .ava then the! #et loc%ed usin# diEerent monitor than non
static methods e.#. both static and non static methods are loc%ed usin#
diEerent monitor in .ava$ and that+s wh! its #rave .ava mista%e to share a
resource between static and non static method in .ava.
;0 Static methods are commonl! used inside utilit! classes e.#.
2ava.util.Collections or 2ava.util.Arra!s$ because the! are easier to access$
as the! don+t need an ob2ect. One o" the popular e?ample o" static
method is thou#h main method$ which act as entr! point "or .ava
pro#rams.
Gead more: http:CC2avarevisited.blo#spot.comC(-1,C11CdiEerence)between)
static)vs)non)static)method)2ava.htmlHi?==,:1?si>IP
Q&- modifer (private vs protected) "or encapsulation'(compare
and contrast)
.ava provides a number o" access modifers to set access levels "or
classes$ variables$ methods and constructors. 9he "our access levels are:
Jisible to the pac%a#e. the de"ault. &o modifers are needed.
Jisible to the class onl! 6private0.
Jisible to the world 6public0.
Jisible to the pac%a#e and all subclasses 6protected0.
#e"ault (ccess )odifer - *o !ey%ord+
De"ault access modifer means we do not e?plicitl! declare an access
modifer "or a class$ feld$ method$ etc.
A variable or method declared without an! access control modifer is
available to an! other class in the same pac%a#e. 9he felds in an
inter"ace are implicitl! public static fnal and the methods in an inter"ace
are b! de"ault public.
,-ample+
Jariables and methods can be declared without an! modifers$ as in the
"ollowin# e?amples:
Strin# version 4 '1.;.1'5
boolean processOrder60 {
return true5
}
.rivate (ccess )odifer - private+
1ethods$ Jariables and Constructors that are declared private can onl! be
accessed within the declared class itsel".
Private access modifer is the most restrictive access level. Class and
inter"aces cannot be private.
Jariables that are declared private can be accessed outside the class i"
public #etter methods are present in the class.
Ksin# the private modifer is the main wa! that an ob2ect encapsulates
itsel" and hide data "rom the outside world.
,-ample+
9he "ollowin# class uses private access control:
public class Io##er {
private Strin# "ormat5
public Strin# #etAormat60 {
return this."ormat5
}
public void setAormat6Strin# "ormat0 {
this."ormat 4 "ormat5
}
}
Lere$ the format variable o" the Io##er class is private$ so there+s no wa!
"or other classes to retrieve or set its value directl!.
So to ma%e this variable available to the outside world$ we defned two
public methods: getFormat()$ which returns the value o" "ormat$ and
setFormat(String)$ which sets its value.
.ublic (ccess )odifer - public+
A class$ method$ constructor$ inter"ace etc declared public can be
accessed "rom an! other class. 9here"ore felds$ methods$ bloc%s declared
inside a public class can be accessed "rom an! class belon#in# to the .ava
Kniverse.
Lowever i" the public class we are tr!in# to access is in a diEerent
pac%a#e$ then the public class still need to be imported.
*ecause o" class inheritance$ all public methods and variables o" a class
are inherited b! its subclasses.
,-ample+
9he "ollowin# "unction uses public access control:
public static void main6Strin#78 ar#uments0 {
CC ...
}
9he main60 method o" an application has to be public. Otherwise$ it could
not be called b! a .ava interpreter 6such as 2ava0 to run the class.
.rotected (ccess )odifer - protected+
Jariables$ methods and constructors which are declared protected in a
superclass can be accessed onl! b! the subclasses in other pac%a#e or
an! class within the pac%a#e o" the protected members+ class.
9he protected access modifer cannot be applied to class and inter"aces.
1ethods$ felds can be declared protected$ however methods and felds in
a inter"ace cannot be declared protected.
Protected access #ives the subclass a chance to use the helper method or
variable$ while preventin# a nonrelated class "rom tr!in# to use it.
,-ample+
9he "ollowin# parent class uses protected access control$ to allow its child
class override openSpeaker() method:
class AudioPla!er {
protected boolean openSpea%er6Spea%er sp0 {
CC implementation details
}
}
class Streamin#AudioPla!er {
boolean openSpea%er6Spea%er sp0 {
CC implementation details
}
}
Lere$ i" we defne openSpeaker() method as private$ then it would not be
accessible "rom an! other class other than AudioPlayer. " we defne it as
public$ then it would become accessible to all the outside world. *ut our
intension is to e?pose this method to its subclass onl!$ thats wh! we used
protected modifer.
Q/- multiple inheritance 62ava does not support but provides
alternative which is inter"ace ) provide defnition M sample code "or
inter"ace0
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class.
An interface is similar to a class in the following ways:
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
The bytecode of an interface appears in a .class file.
nterfaces appear in pac!ages, and their corresponding bytecode file must be in a
directory structure that matches the pac!age name.
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println(Mammal eats)!
"
public void travel(){
System.out.println(Mammal travels)!
"
public int no#$%e&s(){
return '!
"
public static void main(Strin& ar&s()){
MammalInt m * ne+ MammalInt()!
m.eat()!
m.travel()!
"
"