Monday, 10 April 2017

Static Property and Methods

Static Property

Usually class properties don't get created until its object get constructed. But the exception is "Static"


class packet;
  int id;
  static int pkt_id;
endclass

...
packet pkt1, pk2;
pkt1 = new();
pkt2 = new();

pkt1.id = packet::pkt_id++;
pkt2.id = packet::pkt_id++;
...

Output:
pkt1.id = 1
pkt2.id = 2


To access the static property, we have to use "class_name::property".
Static keyword added before the property becomes global through out the class type.


Static Method

class packet;
  int id;
  static int pkt_id;

  static function int unique_id;
     return pkt_id ++;
  endfunction
endclass

...
packet pkt1, pkt2;
pkt1 = new();
pkt2 = new();
pkt1.id = packet::unique_id;
pkt2.id = packet::unique_id;
...

Output:
pkt1.id = 1
pkt2.id = 2

Static method can not access to non static class property. Also there is no "this" for accessing static property or method.

No comments:

Post a Comment