static variables,
static methods,
static block
Lecture 10
Asif Shahzad, Assistant Professor
COMSATS University Islamabad, Lahore Campus
Static Variables
Static Variables
• We often need same value for certain attributes, if we define them as
instance variables, they would consume lot of memory because same
value would be stored multiple times in RAM.
• The solution is to declare it as static variable:
• public static String imagesPath = “d:\data\images”;
• public static String instituteName = “COMSATS University Islamabad”;
• public static String serverIPAddress = “123.45.67.89”
• Static variables are defined inside the class, but we don’t need to
create instance of the class to use them. Only one copy of static
variable is created. All objects share same variable. When value of
static variable change, it changes for all.
Static Methods
• Sometime, we need to define methods that are independent of
object state.
• Static methods are defined inside the class. We don’t need to create
instance of the class to call static methods. We can call static methods
using class name, like:
• Calculator.sum(4,5)
• if sum is static in class Calculator
• Static method can access the static variables, as both are at class
level. They can’t access instance variables. Demo ...
• Static methods can call other static methods, but they can’t call non
static methods.
Static blocks
• Sometime we need to initialize static variables, static block
can be used for this purpose.
• They are generally used, when some computations are
required to initialize static variables.
• Static block is executed, only once i.e. when that class is
loaded. A class can have multiple static blocks.
• Its define using the keyword “static” e.g.
static { /*write some code here */}