• Post Reply Bookmark Topic Watch Topic
  • New Topic

static variable and reference variable example  RSS feed

 
        
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can you show me some exaples like below to understand this topic much better? What are the benefits of using static variable as we can refer to created object emp1.bankid, not class itself Emp.bankid



run:
test
11
5





run:
test
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - non-static variable bankid cannot be referenced from a static context
at test.Person.main(Person.java:23)
Java Result: 1


run:
test
22
22
5
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java® is an object language, so everything defaults to belonging to an object, which means the default is for everything to be not static.
Static means it belongs to the class, so there is something unusual about everything static. Methods are not too difficult to work out. You can, and probably should, make a method static if it fulfils all the following criteria:-
  • 1: It is not a method inherited from an interface.
  • 2: It is not a method in an interface.
  • 3: It takes no information from an object of the class it is in.
  • 4: It alters no information in an object of the class it is in.
  • 5: You do not intend to override the method in a subclass.
  • 6: You are not overriding it from a superclass.
  • Nos 3 and 4 correspond to methods which end with 68 in the most dubious classification of methods known to modern science. Any methods which you might need to use before an instance of the class is created, e.g. the main method, factory methods, usually have to be static.
     
    Campbell Ritchie
    Marshal
    Posts: 56546
    172
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It is rather more difficult to understand static fields. A static field has one value and only one. It is available to all instances of the class and all changes to it become visible to all instances of the class.
    Two examples:
  • 1: Constants. If the value never changes, only 1 copy of the field is needed, so it can be static: public static final int BOILING_WATER = 100;
          You can have private constants, too.
  • 2: Values which are incremented as instances are created. There is an example in this thread.
  •  
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!