Static Concepts

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

static can be

  • variable
  • block
  • method

Static variables

  • 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

Memory Allocation for static variables(1/2)

  • 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();

            new StaticVarDemo();

            new StaticVarDemo();

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

      }

}

On Console   :

Number of Objects : 3

Static Block

  • 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");

      }

      static{

            System.out.println("second");

      }

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

}

On Console   :

first second

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

public class StaticBlock {

                static int staticVariable;

                static{

                                staticVariable =0;

                                System.out.println("initializingstatcVariable ");

                }

                public static void main(String[] args) {

                }

}

 

On Console   :

initializingstatcVariable

Static Methods

  • 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

  1. Block level ( they are local to a block )
  2. Method level  ( they are local to a method )
  3. Object level  ( Instance variables )
  4. Class level   ( static variables )

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

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

Why can’t non-static members be accessed from static context ?

  • Assume that non-static members can be accessed inside static methods

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.

Calling non-static members from static method

public class StaticMethodDemo

{

      public String message = "Hi";

      public void displayName()

      {

            System.out.println("StaticMethodDemo");

      }

      public static void main(String[] args)

      {

            displayName();

            System.out.println(message);

            StaticMethodDemo demo = new StaticMethodDemo();

            demo.displayName();

      }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值