Page 261 - ComputerScience_Class_11
P. 261

Let us see an example given below:
                                 Write a program that uses a static variable increase and a method incre() to increment it.
                  Program 9
                                 Display the value of increase before and after calling the method using two objects.
                   1          class counter

                   2          {
                   3              static int increase=0;
                   4              static void incre()

                   5              {
                   6                  increase++;
                   7              }

                   8              void display()
                   9              {
                  10                  System.out.println("Counter : "+ increase);

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

                  14                  counter ob1=new counter();
                  15                  counter ob2=new counter();
                  16                  ob1.display();

                  17                  ob1.incre();
                  18                  ob1.display();
                  19                  ob2.incre();

                  20                  ob2.display();
                  21              }
                  22          }

                 The output of the preceding program is as follows:

                       BlueJ: Terminal Window - Java
                   Options

                  Counter : 0
                  Counter : 1
                  Counter : 2


                 “increase” is a static variable and it increases by 2 values as two objects are created and only one static variable is
                 created for both objects.
                 c.  Local Variables: These variables are accessed within a function only. The scope of it ends when the method ends
                   (i.e., on encountering the closing brace of the method).
                 d. Constructors: They are the methods that have the same name as that of a class and are used to initialise the
                   instance variables.




                                                                                           Methods and Constructors  259
   256   257   258   259   260   261   262   263   264   265   266