Implicit import (for
example import java.util.*; )
Explicit import – explicit (for
example import java.util.List; )
Fully qualified name – java.utilArrayList
list = new java.utilArrayList
Cohesion ::: Every component is specialized
to do its specific task ex: MVC framework
Model – View Controller
Coupling --- Relation between the
components
Default & lang packages r imported by
default
Static
import – introdued in 1.5ver
Usage of static import reduces length of
the code & improves readability but according to ww programing experts
usage of static import creates confusion & reduces readability
Usually we can access static members by using class names, but
whenever we r writing static import we can access static members directly
without class name.
System.out.println();
Class System{
Static PrintStream out;
}
System is a class present in java.lang
package
Out is a static variable present in system
class of type PrintStream
Println() is a method present in
PrintStream class.
Static import can create ambiguity in case
Import static java.lang.Integers.*;
Import static java.lang.Byte.*;
Max_value() – it will eb ambiguity
How to read inputs in java:::::::
1)
BufferedReader
2)
Scanner
3)
Console
Ø BufferedReader -----
Bufferedreader B = new
Bufferedreader(new InputStreamReader(System.in));
B.readLine();
Ø Scanner in = new Scanner(System.in);
In.nextLine();
In.NextInt();
In.nextFloat();
Ø String name = System.console.readLine();
To write to file
we have :::
Ø FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
Whenever we are wiritng our own classes, we
have to prvide some info about our class to jvm
Top
level classes Should have these modifiers::
Public
Abstract
Final
Default
strictfp
For inner classes applicable modifiers are:
Above +
Private
Protected
Static
Access specifiers vs access modifiers::
Public, private protected default
Are considered as specifiers except these
remaining as considered as modifiers.
But this rule is applicable only for old
lang like c++but not in java
In
java all are considered as modifiers only
There is no word like specifiers.
Public classes
We
can access the class from anywhere
Default classes:
If a class declared as default, we can
access that class only within the current package i.e from outside package we
cant access. Hence default access is also known as package level access.
Final modifier::
Final is a modifier applicable for classes,
methods & vars.
Whatevere methods parent has by default
available to the child through inheritance.
If the child not satisfied with parent
method’s implementation, then child is allowed to redefines dat methods the he
can redefine by overriding.
If the parent class method is declared as
final then we cant override that method in the child class, cu zits
implementation is final.
Method
overriding not possible for final methods
Final class::
If a class declared as final we can’t
extend functionality of dat class ie we cant create child class for dat class.
i.e inheritance is not possible for
final classes.
****** Every method present inside final
class is always final by default. But every var present inside final class need not be final.
The main adv of final keyword is we can
achieve security & we can provide unique implementation, but the main
disadv of final keyword is we r missing key benefits of oops ex : polymorphism,
inheritance.
Abstract modifier
Abstract method
Following are illegal combination of
modifiers with abstract modifier
Final
Static
Private
Native
Strictfp
Synchronized
Public & protected == allowed
Abstract class
For
any java class if we r not allowed to create an obj because of (partial
implementation) such type of class we have to declare with abstract modifier.
Ie for abstract classes instantiation is not possible.
*****abstract
classes cannot be instantiated. (It is abstract no proper methods.)
Abstract class vs abstract method
If
a class contains at least 1 abstract method then compulsory we shud declare
class as abstract otherwise we will get compile time error.
Reason --- If a class contains atleast
1 abstract method then imeplemntation is not complete & hence it is not
recommended to create obj. To restrict obj instatiation compulsory we shud
declare class as “abstract”
Even
though class does not contain any abstract methods still we can declare class
as abstract if we dont want instatiation ie. Abstract class can contain 0
number of abstract methods also.
Ex:
HTTPServlet class is abstract but it does not contain any abstract methods.
Every
adapter class is recommended to declare as abstract but ti doesn’t contain any
abstract method.
Class
p {
Public
void m1();
}
----
missing method body or declare abstract
Public
abstract void m1{}
-----abstract
methods cannot have a body
Class
p {
Public
abstract void m1();
}
--------P
is not abstract and does not override method m1 in P
If
w eare extending abstract class for each & every abstract method of parent
class v shud provide implementation otherwise we have declare child class as abstract.
In
this next level child class is responsible to provide implementation.
Final vs abstract
Abstarct methods compulsory we shud override in child
class to provide implementation, where as we cant override final methods. Hence
final abstract combination is illegal combination for methods.
For
final classes we cant create child class where as for abstract classes we shud
create child class to provide implementation. Hence final abstract combination
is illegal.
*****Abstract
clclass can contain final methods where as final class cant contain abstract
method.
VALID
Abstract
class Test {
Public final m1() {}
}
INVALID
Final class Test {
Public abstract m1()
}
It is highly recommended to use abstract modifier because
it promotes several OOP features like inheritance & polymorphism. Where as
final does not support.
Strictfp – Strict floating point –
*introduced
in 1.2V
*
We can use it only for classes & methods but not for variables.
Usuaully
the result of floating point arithematic is varied from platform to platform.
If we want platform independent results for fp arithematic then we shud go for
strictfp modifier.
For
ex:
10/3
=== 3.3333333 – 16bit processor
3.3333333333333333
– 32 bit exx
If
a method declared as strictfp – all floating point calculations has to follow
IEEE754 standrd so dat we will get platform independent results.
Abstratc
modifier never talks abt implementation where as strictfp always talks abt
implementation. Hence abstartc strictfp combination is illegal for methods.
Strictfp class ------
If a class declared as strictfp then
every floating point calculation present in every concrete method has to follow
IEE 754 standar so dat we will get platform independent results.
We can declare abstract strictfp combination for classes ie.
Abstract strictfp combination is legal for classes but illegal for methods.
Abstract strictfp class m{ -- VALID
}
Abstract strictfp void m1() {} – ILLEGAL
Member modifiers::
Method /var level modifiers
If a member is decalred as public &
class is also public we can access the method from anywhere based on visibity
(if class is imported proeprly).
But if member is public & class is
default – the method will not be visible.
Even though m1 method is public we cant
access from outside package cuz corresponding class is not public. If both are
public den only we can access dat method from outside package.
Default members:
If a member declared as default we can
access dat member only within the current package. Form outside the package we
cant access. Hence default acces sis also known as package level access.
Private member::
If a member is private, then we can access
d member only within class. Ffrom outside class we cant access.
Abstarct methods shud be available to the
child classes to provide implementation. Wheras private methods r not available
to the child classes. Hence private
abstract combination is illegal for methods.
Protected
members:
The most misunderstood modifier in java.
Protected modifier is never applied for class.
Protected = default +kids
If a member declared as protected we can
access that member only within that package + only child of that package.
We can access protected member within curr package
anywhere using parent / child reference. But we can access protected member in
outside package only in child classes & we should use only child
reference only. Ie. Parent refence cannot be used to access protected member
from outside package.
We can access protected member from outside
package only in child classes and we should use that child class reference only
From D class if we want to acess we should
use D class refence only.
Visibility
|
Private
|
Default
|
Protected
|
Public
|
Within same class
|
YES
|
YES
|
YES
|
YES
|
From child class of same package
|
NO
|
YES
|
YES
|
YES
|
From Non child class of same package
|
NO
|
YES
|
YES
|
YES
|
From child class of diff package
|
NO
|
NO
|
YES – Only with particular child reference
used
|
YES
|
From non child class of diff package
|
NO
|
NO
|
NO
|
YES
|
Private < default
< protected < public
Final variables
Final instance variable
If
val of var is varied from obj to obj such type of vars are called instance
vars.
For
every obj a sep copy of instancevar will be created
JVM
will initialize.
If
instance var is decared as final – it should be compulsorily initialzed
whether we use / not and jvm wont provide default values.
Class Test {
Final int x; - CE var x might not have
been initialized.
}
For
final instance var copulsary we shud perform initialization before constructor
completion
The
following are various places for initialization ::
1) At the time of decalarion
2) Inside instanc eblock
3) Inside constructor
These
are the only possible places to perform initialization for final instance
variables;
If
w eare trying to perform initialization anywhere else den we will get compile
time error.
2)
final static variables
Ex:
college name for all students will be same --- the var canbe created for a
class –
If
the val of a var is not veried from obj to obj such type of vars are nto
recommended to declare as instance vars. We have to declare those vars as class
level by using static modifier.
Instanc
– for very obj sep copy is created
Static
– created per class & shared by every obj of d class.
For
static vars it is not required to perform initialization explicitely. JVM will
always provide default values
If
using final --- please provide value before using it!!!
RULE
::: For final static vars compulsory we shud perform initilizaition before
class loading completion. Ie the following r varus places for this.
1) At the time of declaration
2) Inside static block
Instance
block static
block
{ static
{
} }
For final local variable
--- we may not initialize if we are not using it!
Formal params of a method
simply access local vars of the method hence formal params can be declared as
final. If forma param is declared as final within a method we cant perform
reassignment.
Static
modifier
Applicable
only for methods & vars but not for classes.
We
cant declare top level class with static modifier. But we can declare inner
class as static. Such type of inner clases are called static inner classes.
If a parent class has static method and child classextending parent class
also uses same method name generally it wud be called method overriding. But if
the methods are static then it is called method hiding in java.
We
cannot use Super keyword in case of static context--------------
Abstract static combination is illegal
Synchronize
If multiple
threads trying to operate simultaneously on the same java obj then der may be
chance of data inconsistency problem di sis called race condition. We can
overcome this problem by using Synchronized keyword. If a
method / block declared as synchronized then at a time only 1 thred is allowed
to execute dat method / block on the given obj so dat data inconsistency
problem will dbe resolved
The main dis of synchronized keyword is it increases waiting
time of threads and creates performance problms. Hence if deris not pseific req
iden it is not recommended to use
synchronized keyword.
Synchrmized shud contain impelemention abstract doesnot
contain any mplemnta
Abstarct
Synchrnized is illegal combination for methods.
Native modifier:
It is modifier
applicable only for methods. We cant apply anywhere else.
The methods which are implemented in non java (mostly c,
c++) are called native methods. Or foreign methods.
The main objectives of this keyword are
1)
TO improve performance of the system
2)
To achieve machine level / memory level
communication
3)
To use already existin legacy non java
code.
Psuedocode to use native code in java
1)
Import libraries in static block
2)
Static {
System,library
}
3)
Declare native method – public native
void sum();
4)
Invoke the method
For native methods implementaiotn is already available in
old lang c
Native methods do not have body
Native abstract is illegal comb for methods.
Transient
Keyword
Modifier
applicable only for variables.
We
can use transient keyword in serialization context.
Serailization
– saving obj to file
At
the time of deserialization if we do not want to save the value of vr sue to
security constraint. At the time of serialization jvm ignores original values
of transient vars& and show default
value. Heance transient means not to serialize.
Volatile
keyword:
Deprecated
–In multithreading new copy of obj is
created for every thread to prevent data inconsistency problem. For 10k threads 10k copies
Final
volatile combination is illegal
Allowed
modfiers::
Local
Variable – final
Constructor
– public, private , protected, default
Only
for Methods – native –
Only
for variables – volatile & transient
Classes
but not for enum ---- final & abstract
INTERFACES::
Intro:
Def1:
Any service requirement specification (SRS) is interface
Ex1:
JDBC api acts as requirement specification to develop database driver. DB
vendor is responsible to implement the jdbc api.
Def2::::
From client point of view interface defines set of services wht he is
expecting. From service provider point of view the set of service swhta he is
offering. Hence any contarct between client & service provider is
considered as an interface
Any
service requirement specification or any contract between client & service
provider OR
100%
pure abstract clas sis nothing but interface.
1) A class can extend only one
class at a time
2) An interface can extend any
number of interfaces simultaneously
Interface
{}
Interface C extends A, B {
}
3) A class can implement any
number of interfaces simulataneously.
4) A class can extend another
class & can implement anynumbe rof interface simulataneouly.
Clas A extends B implements C, D, E{}
Every method present inside interface is always
public & abstract whethere we are declaring or not. -------- This is make
this available to every implementation class.
Public --- to make the method available in every
implemented class
Abstract – as pe rinterface concept the method has
to be abstract.
Inside interface the
following method declarations are equal.
Void m1()
Public void m1();
Abstract void m1();
Public abstract void m1();
As every interface method is always public & abstract
we cant declare interface method with the following modifiers.
·
Private
·
Protected
·
Static
·
Strictfp
·
Final
·
Synchronized
·
Native
Which of the following method declratios are allowed
inside interface:
Only last one valid.
---------------------------------------------------
METHOD HIDING comes only into picture of inheritance
where we use extends where child extends from parent:::::
Class Animal {
Public static void main(String[] args) {sop(“Animal”);}
}
Class cat extends Animal {
Public static void main(String[] args) {sop(“cat”);}
}
----------------------------------------------------
Interface variable::::_
An interface can contain variable. The main purpose of interface
variable is to define requirement level constants
Every interface variable is by
default
Public static final ---- whether we are declaring or not
Public ----To make this available to every implentation
class
Static ---Without existing object also implementation
class has to access this variable.
Final – if one class obj changes value then remoainign
classes also will be impacted.
Hence within the interface the following var declaration
are equal.
We cannot use these modifiers as every interface var is
public static final
Priate
Protected
Transient
Volatile
?>>>>For interface vars compulsory we shud
perform initialization at the time of declarion otherwise we will get compile
time error
Inside interface which of following var declaration are
allowed.
Only public static final int x=10;
Inside
implementation class we can access interface variables but we cant modify
values.
Method naming conflicts::::::
1)
If 2 interfaces contain a method
with same signature & same return type then in the implementation class we
have to provide implementation for only 1 method.
2)
If 2 interfaces contain
methods with same name but diff argument types then in the implementation class
we have to provide implementation for tboth the methods as below and these
methods acts as overloaded methods.
If 2 interfaces contains a
method with same signature but diff return types then it is impossible to
implement both interfaces simulateously. (If return types r not covariant)
Can java implement any no
of interfaces simultaneously -----
Yes except above particular
case whr 2 interfaces have same method names with diff return type
Method variable conflicts
2 interfaces cancontain a var with a same name and
der may be chance of var naming conflicts . We can solve this problem by using
interfacename as it is static
Marker Interface / ability
interface / tag interface
If an interface does not
contain nay methods and by implementing that interface if our objects get some
ability such typ of interfaces are called marker interfaces.
Ex: serializable
Clonable
Random access
Single thread model
By implementing serializable interface our objects can be
saved to the file and can travel across the network.
Without having any methods how marker interfaces provide
the ability??
>>Internally JVM is responsible to provide required
ability.
Why JVM is providing required ability in marker
interfaces??
>> To reduce complexity of programming & to
make java lang as “Simple”
Is it possible to create our own marker interface???
>>We can create but customization of JVM is
required.
Adapter classes
It is a simple java class
that implements a interface with only empty implementation.
For every each and every
method of interface compulsory we shud provide implementation whether it is
required / not required
Differeences between interface
& abstract classes::::::::::::
Interface
|
Abstarct
Class
|
This is a requirement
specification and hence has only
abstract methods
|
This is partial
implementation and hence has both abstract & concrete methods
|
The default modifier for
all methods is public abstract
|
All methods need not be
public abstract
|
Since abstract modifier
is used for methods – these cannot be applied to methods – private,
protected, default, strictfp, final
|
Any modifier can be
applied to methods
|
All variables are public
static final
|
Variables can be of any
type
|
Since variables are
public we cannot use private, default, protected. Since they are final we
cannot use transient, volatile
|
Variables can be of any
type
|
No constructors
|
It has constructor
|
No static block ,
instance block
|
It can contain static
block & instanc eblock
|
Either directlyor indirectly for abstract class.
Anyways we cant create object fot for abstract
class & interface but abstract class can contain constructor but interface
doesn’t contain constrcor --???
The main purpose of
constructor is to perform initialization for the instance vars
Abstract class can contain
instance var which are required for child obj. to perform initialization
ofthoseinstance variables constructor is required for abstact class.
But evry var present inside interface is always public
static final whether we r declaring or not & der is no chance of existing
instance var inside interface. Hence constructor concept is not required for
interfaces.
Whnever we r creating child
class objects of abstract class parent obj wont be created but only parent
constructor will be executed for the child obj purpose only.
Inside interface every
method is always abstract & we can take nly abstract methods in abstract
class also but that Is not good programming practice. Then wat I sthe
difference btn interface & abstract class ie is it possible to replace
interface wid abstract class
While
extending abstract class we r not allowed to extend any other clas hence we
will loase inheritance benefit
When we impement interface we can
implement 1 or many & hence we will not lose inheritance
In asbtarct class Test t = new Test ()
New ---- create obj
Constructor – initialize object
1st obj will be created using new operator &
then initialization will be performed by constructor
Whnever we are creating child class objects both child &
parent constructor will be executed.
No comments:
Post a Comment