Unit 1 ( Prog 2) : Test Access Modifiers

By | June 2, 2013

Use of access modifiers and class properties…

/* 
 * Question : value of rightFirst will be always one third of leftFirst or not ?
 * NO because both are public, no need to use setLeft() method for that
 * those are directly accessible…:p
 * but it is true in case of class ValueSecond
 */
class ValueFirst {
          public int leftFirst;
          public int rightFirst;
          public void setLeftFirst(int leftNum) {
                    leftFirst = leftNum;
                    rightFirst = leftNum / 3;
          }
          public String printValues(){
                    return “left of ValueFirst Class : ” + leftFirst + “nright of ValueFirst Class : ” +  rightFirst ;
          }
         // remaining function code goes here.
}
class ValueSecond {
          private int leftSecond = 9;
          private int rightSecond = 3;
          public void setLeftFirst(int leftNum) {
                    leftSecond = leftNum;
                   rightSecond = leftNum / 3;
          }
          // remaining function code goes here.
          public String printValues(){
                   return “left of ValueSecond Class : ” + leftSecond + “nright of ValueSecond Class : ” +  rightSecond ;
          }
}
public class testAccessModifier {
          public static void main(String a[]) {
                    ValueFirst v1 = new ValueFirst();
                   // here it goes…
                   v1.leftFirst = 5;
                   v1.rightFirst = 10;
                   System.out.println(v1.printValues());
                   ValueSecond v2 = new ValueSecond();
                    // whoah…compilation error in next line after removing comments…:D
                    // v2.leftSecond = 5;
                   // v2.rightSecond = 10;
                    v2.setLeftFirst(9);
                    System.out.println(v2.printValues());
          }
}
/* Check access modifiers of the properties of function first if you find an easy question.
 * it might be twisted…:p 
 */

 

One thought on “Unit 1 ( Prog 2) : Test Access Modifiers

  1. Veaceslav Grec

    Good example for testing access modifiers. In practice however, you should tend to minimize the visibility of your fields, providing getters and setter methods.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *