Tuesday, 21 August 2018

Static Members


Static Members
Static members are like global variables which are sharable across all the objects of the class and will maintain their values between objects.
Features:
  • They should be declared with the help of keyword “static”.
  • They are accessible across the entire class objects.
  • They are generally used to persist the value between objects calling.
  • If they are declared as public they can be accessible with the help of classname instead of object name.
//Program on Static Members
class staticdemo
{
            int objno;        
            static int objcnt;          
            void hitcount( )
            {
                        objno=++objcnt;
            }
            void showhits()
            {
                        System.out.println("This page has been hit for "+objcnt);
            }
            void showposition()
            {
                        System.out.println("Client " + objno+  "/" +objcnt);
            }
}
class Implstatic
{
            public static void main(String []args)
            {
                        staticdemo s=new staticdemo();
                        staticdemo t=new staticdemo();
                        staticdemo v=new staticdemo();
                        s.hitcount();
                        t.hitcount();
                        v.hitcount();
                        v.showhits();
                        s.showposition();
                        t.showposition();
                        v.showposition();
            }
}
Output:
D:\sysvol>javac Implstatic.java
D:\sysvol>java Implstatic
This page has been hit for 3
Client1/3
Client2/3
Client3/3

Static Methods:
Similar to static members, within the class concept we can have static methods, which are capable of accessing only static members, and can be called with the help of class name.

No comments: