jueves 11 de agosto de 2011

Basic modifiers you should know before programming in Java

The static keyword can be used in 4 scenarios

1) static variables

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.

2) static methods

  • It is a method which belongs to the class and not to the object(instance)
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can call only other static methods and can not call a non-static method from it.
  • A static method can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.
  • A static method cannot refer to "this" or "super" keywords in anyway


3) static blocks of code.

The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM

class Test{

static {

//Code goes here

}

}

4) static Inner class.

Make an inner class top-level class


The final keyword can be used in 4 scenarios

1) final variables

  • It is a variable which can not change its value

2) final method

  • It is a method which can not be overriden and dinamically looked up (Polymorphism)

3) final field

  • It is a variable which can not change its value. Static final fields are compile-time constants.

4) final class

  • It is a calss which can not be subclassed



Modifiers keyword for access levels


Access Levels
Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N




The transient keyword can be used for a field

1) transient field

  • It is a field to not to be serialized with the object serialization.


The synchronized keyword can be used for a method

1) synchronized method

  • For a static method, a lock for the class is acquired before executing the method. For a non-static method, a lock for the specific object instance is acquired.



The native keyword can be used for a method

1) native method

  • It is a method witch is platform-dependent. It doesn't have body, only signature.


0 comentarios:

Publicar un comentario en la entrada