Lecture 3
Lecture 3
Overloading/ Instance
Block and Static Block
Presented by: Shereen Sikander
Constructor Overloading
• Constructor overloading is a technique that allows a class to
have multiple constructors with different parameters.
• Conditions for constructor overloading:
1) The number of parameters should be different.
2) The type of parameters should be different.
Example via code..
Private constructor / default
constructor code
Private constructor / default
constructor code
Instance Block
• An instance block is similar to a method which has no name. It can be
written inside a class only and not inside a method.
• Note:
1. It always executes before a constructor.
2. We can use variables inside the instance block and not a method.
3. Instance block can access static as well as non-static variables.
4. It is a usual practice to write time-consuming code inside an instance
block like: JDBC connectivity string.
5. For an instance block to execute, it is important that a class MUST have
an object.
Instance Block Continued
• Syntax:
Class A{
{
//code
}
}
Instance Block Continued
Static Block
• It is a kind of block in JAVA that gets executed when loading a .class
file into JVM memory.
A.java Class Loader
JVM
Byte Code Verifier
Javac Execution Engine
A.class
Static Block Continued..
• Syntax:
Class A {
Static {
//code
}
}
Static Block Continued.
Note:
1. Code that is written in a static block executes only once because static block
has nothing to do with an object.
2. Static block can be executed before instance block or constructors of a class.
3. In versions below JDK1.6 it is possible to print on console without writing a
main method only through static block.
4. Static methods/functions and variables can be accessible via Class name.
5. Static block can only access static variables.
JDK version below 1.6
JDK version 1.6 and above
Static Block Continued
Write an output of the following
code
Output
Instance Block Vs Static Block
Keyword is not required while writing an Static keyword is required while writing a
instance block static block.
Static and non-static variables can be Only static variables can be accessible in
accessible in this block this block