Thursday, March 29, 2012

Chapter 4: Declarations and Access control

Chapter 4: Declarations and Access control

4.1. Java source file structure:
   
                A java program may contain any number of classes but at most one class we can declare as the public.
            If there is any public class the name of the program and the name of the public class must be matched. Otherwise compiler gives compile time exception.
           If there is no public class any class name we can use as the file name.Packages in java are encapsulation mechanism in order for resolving naming conflicts.By using package we can group related classes, interfaces into a single module.It is convention to name the packages use their internet domain in reverse.

           In any java file more than one package statement is not allowed and if we are specifying any package statement it should be the first statement in the file.





Explicit class import is highly recommended in real time because to identify which
classes are using in the code.
The correct sequence of statements inside java program is
Package statement------------almost one statement is allowed
import--------------------------any number of statements are allowed
class/interface---------------any number of statements are allowed

If any class is available in two packages and we include those two packages in the
program then compiler will show the compile time exception. To solve this type of
problem we should go for fully qualified name.

import statement is totally compiling time issue. More number of imports, more will be
the compile time. There is no effect of increasing number of imports at run time.
The order in which compiler resolves the import statements is as follows
Explicit class imports
Current package imports
Implicit class imports.

4.2. Class lever access modifiers:

         The access modifier or specifier of a class describes the complete behavior of our class.
The only allowed modifiers for the top level classes are public, default, final, abstract
and strictfp.
If we are using any other modifiers like private, protected, synchronized ---- we will get
a compile time exception.
Public class: If a classed declared as the public we are allowed to access that class
from any where.
Default class: If a class declared as default we can access that class only in the current
package.
Final class: If we are declaring a class as the final we are not allowed to create child
class. This is for achieving security or safety. But because of using final keyword we will
Miss one of the key benefits of object oriented programming (reusability) that is why it
is not recommended to go for final key word unless security is not required.
If we can declare a class as the final all the methods present in the class will
become final. No chance of overriding instead of declaring a class as the final it is
recommended to declare the methods as the final.
Final class we cannot create child class. Final method we cannot override in child
class. Final variable is constant.
Advantage of final is safety and security.
Disadvantage of final is reusability.
Abstract keyword:
Abstract is a keyword which can be applied only for methods and classes we never allow
to use abstract keyword for the variables.
Abstract method means the method without having any implementation. Child class is
responsible for implementing abstract methods of the parent class.
Abstract method can be declared as
abstract void m1( ); [ ; is mandatory ]
If a class declared as the abstract we are not allow creating an instance of that class.
If a class contains at least one abstract method then we should declare the
corresponding class as the abstract.
An abstract class need not contain any abstract method.
final and abstract is illegal combination for the methods and classes.
A final class never contains any abstract method but an abstract class can contain final
methods.
Some illegal combinations are given below
abstract-final
abstract-static
abstract-synchronized
abstract-native
abstract-staticstictfp
abstract-private
32
Strictfp (strict floating point): This is the keyword which can be applied for the
classes as well as methods. We cannot apply strictfp for the variables.
Strictfp public void m1( )
{
System.out.println(10.0/3);
}
The result of floating point digits depends on OS. To reduce this declares the method as
strictfp. If a method declared as the strictfp all the floating point calculation has to follow
IEEE754 standards.
If we are declaring method as the strictfp we cannot expect the result because it
depends on the underline platform.
Abstract and strictfp is illegal combination for the methods
Abstract and strictfp is legal combination for classes.
For the constructors the only allowed modifiers are public, default, private and
protected. The remaining modifiers like static, final, abstract ---- are not allowed.

4.3. Member access specifier:
4.3.1. Public members:
If a member declared as the public we are allowed to access that from anywhere. Before
checking member visibility we should always check class visibility.
Observe the below program:
If class A is not defined as a public we will get compile time exception even m1() is
public.





4.3.2. Default members:
If a member declared as the default with in the package only we can access
4.3.3. Private members:
If a member declared as the private we should access only in current class only.
Outside the class it is not visible.
Private methods cannot be overridden in the child class
Private and abstract is axzillegal combination for the methods .Because private methods
are not available in the child class for overriding (for implementing).
4.3.4. Protected members:
The protected members are available with the current package any where but outside
the package only in child classes.
Protected = default + child classes
The protected members we can access with in the package either by using parent class
reference or by using child class reference. But from outside the package we can access
protected members only by using child class reference.
Private<default<protected<public.




In general the data members are declared as the private and the methods are declared
as public.


4.4. Final Variables:
Instance variables, static variables and local variables.




4.4.1. Final Instance variables:
If we are not performing initialization default values will come for instance variables.
For final instance variables we should perform initialization otherwise we will get compile
time exception saying variable might not have been initialized.
We will initialize the final variables
At the time of declaration
In the instance initialization block
In constructor
For final instance variable we should perform initialization before the constructor
compiles.
We cannot perform initialization for the final instance variables inside the methods.
4.4.2. Final static variables:
For the static variables no need to perform initialization. They will get default values. But
final static variables never get default values. Before class loaded into the memory we
should perform initialization. i.e we can perform initialization for the final static variables
in the following places.
At the time of declaration
Inside static initialization block.

4.4.3. Final Local variables:
If we are not using even though local variable is the final no need to perform
initialization.
Before using a local variable we should perform initialization (either final or non final
local variable)
The only modifier allowed for the local variables is the final.
We never declare any local variable with private or others.
The variables which are declared as the formal arguments are simply acts as local
variables of that method. The only allowed modifier for those variables is final.


Class Sample
{
static void m1(final int 1, int j)
{
i=10 ------------ invalid
j=20; ------------valid
}
Public static void main(String args[])
{
m1(30,300);
}
}
We should not reinitialize final local variable.


4.5. Static variables:
The keyword static we can apply for variables, methods, classes (not for top level
classes) and blocks.
Static variables are class level variables in general static variables are used for defining
constants.
class Student
{
int i=10;
static int j=20;
public static void main(String args[])
{
Student s1 = new Student();
S1.i=100;
S2.j=2000;
Student s2 = new Student();
System.out.println(s2.i); --------------------10


System.out.println(s2.j); --------------------20
}
}

1. For instance variables a separate copy will create for every instance but in the case
of static variables, a simple global copy will create and shred by all instances.
2. We can access static variables either by object reference or by class name (be class
name is the recommended). We can change the value of static variables by using
object reference. In that case the changes will reflect for all the remaining instances
that’s why in general static variables always associated with final to define constants
so that the objects will get read access only.
3. Static methods should have implementation but abstract methods should not have
implementation hence static and abstract illegal combination for the methods.
4. Static and abstract combination, we never apply for top level classes but we can
apply for nested classes.
5. Non-static variables cannot refer from the static context directly violation leads to
compile time exception.
Ex1) Consider the following declarations
int i =10;
static int j =20;
public void m1()
{
System.out.println(i);
}
public static void m1()
{
System.out.println(i);
}
Ex2) which of the following are valid statements in the same class?
(1 & 3) instance members we can access directly from instance environment
(1 & 4) invalid because we cannot access instance members directly from the static
members.
(2 & 3) static members can be accessed from any where (either from instance
environment or from static environment.
(2 & 4) static members can be accessed from static environment.
6. Static methods can be overloaded but cannot be overridden.


4.6. Synchronized:
The keyword synchronized we can apply for methods and blocks. On any objet at time
only one thread is allowed to execute synchronized methods or synchronized blocks on a
particular object.
The advantage is security and data consistency
The disadvantage is a big performance problem because of synchronized keyword.

4.7. Native:
Native is a keyword which can be applied only for methods.
The purpose of introducing native methods in java is for improving performance of the
system and for utilizing legacy systems
The native methods are the methods which are implemented in non java lick c, c++ etc
Native methods are also called foreign methods
Java provides in built support for native methods by java native interface (JNI)
Native and abstract is illegal combination for the methods.
Native and strictfp is also illegal combination for the methods.
We are allowed to override a native method as non native method.

4.8. Transient:
Transient is the keyword which can be applied only for variables.
Transient means not to serialize while storing the stat of object to a file JVM ignores the
value of transient variables, instead of considering original values JVM will take default
values for the transient variables.
We can apply transient for the static variables but there is no impact the original values
will store into the file and we will get the same values.
We can apply transient and final simultaneously for the variables but there is no impact
of transient on the final variables.

4.9. Volatile:
Volatile is the keyword which can be applied only for variables.
Volatile variable means its value will change frequently for achieving synchronization at
the variable level, we can use volatile keyword.
JVM will create a separate private copy of this variable for every thread so that we can
prevent data inconsistency problems.
Volatile keyword is completely outdated now a day because it will create performance
problem.
Volatile and final is illegal combination for the variables.

4.10. Interfaces:
An interface defines a contract between client and service provider. It describes
the set of services (with out implementation details) provided by service provider to the
client. By using interface concept we are hiding implementation details so that we can
achieve security and we can change internal implementation with out effecting outside
world.
interface Sample
{
public void abstract m1( );
}
The only allowed modifiers for the interface are public, default and abstract.
public interface Sample{ }
abstract interface Sample{ }
public abstract interface Sample{ }

interface methods:
All the interface methods are by default public and abstract. Hence the following
declarations are equal.
void m1();
public void m1();
public abstract void m1();
abstract void m1();
The following declarations are illegal inside an interface.
private int m1();
protected int m1();
final void m1();------------------abstract-final
strictfp void m1(); --------------abstract-strictfp
static void m1(); ----------------abstract-static
static void m1();
native void m1();
100% pure abstract class is interface
While implementing interface methods in any class we should declare the method as
public otherwise it gives compile time exception.
The class which is implementing any interface must responsible for implementing all the
methods present in that interface, otherwise the class should be declared as abstract.
interface                                                   abstract
All the methods must be abstract.                it may contains some concrete methods also
Constructor concept not
applicable for interfaces                  constructors must be present inside an abstract class
A class can extend only on class at a time.      An interface can extend any number of interfaces at a time.
A class can implements any number of interfaces at a time.
All the interface variables are by default public, static and final. We are not allow to
change the value of interface variable in the implemented class.
Ex:
interface abc
{
int i=10;
}
class xyz implement abc
{
public static void main(String args[])
{
i=100;
System.out.println(i); -----------compile time exception
}
}

For the interface variables we should provide implementation at the time of declaration
only otherwise it will give compile time exception.
We never allowed declaring interface variables as volatile or transient violation leads to
compile time exception.
All the following declarations are equal inside an interface.
int i=10;
public int i=10;
public static int i=10;
public static final int i=10;
final int i=10;

Tag interfaces: If the interface is marked for some ability such type of interfaces are
called marker ability or interface ability or tag reference.
Ex: serializable interface, clonable interface, comparable interface
If the interface does not contain any method by default the interface is marker interface
or tag reference. Even though the interface contains some methods still we can use
marker interface, if that interface is marked for some ability.

Case1:
interface Left
{
public void m1();
}
interface Right
{
public void m1();
}
class Sample implements Left,Right
{
public void m1()
{
System.out.println(“Success”);
}
}
If a class implements two interfaces Left and Right which contain the methods with the
same name and arguments and same return type then only one implementation is
enough.

Case2:
interface Left
{
public void m1();
}
interface Right
{public void m1(int i);
}
class Sample implements Left,Right
{
public void m1()
{
System.out.println(“Success”); over loaded methods
}
public void m1(int i){}
}
If method signature is different we should provide implementation for both methods.

Case3:
interface Left
{
public void m1();
}
interface Right
{
public void m1(int i);
}
class Sample implements Left,Right
{
int i;
public void m1()
{
System.out.println(“success”); overloaded methods
}
public int m1(int i)
{
System.out.println(i);
Return I;
}
}
If method signature is different we should provide implementation for both methods.

Case 4:
interface Left
{
public void m1();
}
interface Right
{
public int m1();
}

class Sample implements Left,Right
{
int i;
public void m1()
{
System.out.println(“Success”);
} Compile time exception
public int m1()
{
System.out.println(i);
Return i;
}
}
If both interfaces contain method with same signature but different return types, we are
not allowed to implement two interfaces simultaneously in the same class.


















No comments: