天天看点

Static Concepts

Q. What are the different things that can be static ?

static can be

variable

block

method

<b>Static variables</b>

Static variables are Class variables

private static int counter ;  // creates a class variable

private int index;           //creates an instance variable

They are initialized when the class gets loaded

Static variables are used when you want to keep a value across instances of a class , e.g.,

Number of objects that are getting created

Number of users visiting your website

Initialization

e.g., private static int counter =2;  

Can be initialized using static block

<b>Memory Allocation for static variables(1/2)</b>

Let us look at the class StaticVarDemo once again :

public class StaticVarDemo {

      private static int staticCount;

      public StaticVarDemo(){

            staticCount++;

      }

      public static void main(String[] args) {

            new StaticVarDemo();

            System.out.println("Number of Objects : "+staticCount);

}

<b>On Console   :</b>

<b>Number of Objects : 3</b>

<b>Static Block</b>

Can be used to initialize static variables to some initial value

                static int counter;

                static{ counter =0; } 

Cannot  be used to initialize non-static member variables

Can be used to add preprocessing if required

Static block gets executed when class gets loaded

If multiple static blocks are present in the class then their order of execution is their sequence in the class

public class SequenceDemo {

      static{

            System.out.println("first");

            System.out.println("second");

      public static void main(String[] args) {}

<b>first second</b>

All the static blocks gets executed in the sequence they appear in the class

To do some logical processing

To print a message when variable is getting initialized

<b>public class StaticBlock {</b>

<b>                static int staticVariable;</b>

<b>                static{</b>

<b>                                staticVariable =0;</b>

<b>                                System.out.println("initializingstatcVariable ");</b>

<b>                }</b>

<b>                public static void main(String[] args) {</b>

<b>}</b>

<b> </b>

<b>initializingstatcVariable </b>

<b>Static Methods</b>

Static methods are class level methods i.e., they are shared among all the objects of the same class       

A Static context(static blocks or methods) CANNOT access non-static members

class  StaticDemo{

                int counter;

                public static void main(String[] args){

                counter = 0;

Error :  counter is not static so cannot be accessed inside the static method

Non-static methods can access the static members

There are four important scope levels in Java . Below is the list from small to largest

Block level ( they are local to a block )

Method level  ( they are local to a method )

Object level  ( Instance variables )

Class level   ( static variables )

Simple rule says that , variables defined in large scope can be accessed in smaller scope but reverse is not true.

<b>Why can’t non-static members be accessed from static context ?</b>

<b>Assume that non-static members can be accessed inside static methods</b>

class StaticDemo

{

      private int counter = 0;

      public StaticDemo(int counter)

      {

            this.counter = counter;

      public static void changeCounter()

            counter = 400;

      public static void main(String[] args)

            StaticDemo demo1 = new StaticDemo(200);

            StaticDemo demo2 = new StaticDemo(100);

            StaticDemo.changeCounter();

Which counter is changed , of demo1 or demo2 ?

Embedded demo must be seen first to understand the slide.  If non-static members are allowed to be accessed from static context then it cannnot be decided to which object does the member variable belong to. So if in some way we can provide the object to the member vairable , then member can be accessed from static methods. For example see the next slide.

<b>Calling non-static members from static method</b>

public class StaticMethodDemo

      public String message = "Hi";

      public void displayName()

            System.out.println("StaticMethodDemo");

            displayName();

            System.out.println(message);

            StaticMethodDemo demo = new StaticMethodDemo();

            demo.displayName();