How to modify the objects using java classes

By: Issac Viewed: 153257 times  Printer Friendly Format    


In this tutorial we are going to see how to modify the objects using java classes. 

class ClassA
   {
  private int data;

  public ClassA(int startingVal)
  {
    data = startingVal;
  }

  public ClassA add(int x)
  {
    data += x;
    return this;
  }

  public ClassA multiply(int x)
  {
    data *= x;
    return this;
  }

  public ClassB makeClassB()
  {
    return new ClassB(data);
  }
}

public class ClassB
 {

  private int data;

  public ClassB(int startingVal)
  {
    data = startingVal;
  }

  public int read()
  {
    return data;
  }

  public boolean nonzero()
  {
    return data != 0;
  }

  public ClassB add(int x)
  {
    return new ClassB(data + x);
  }

  public ClassB multiply(int x)
  {
    return new ClassB(data * x);
  }

  public ClassA makeClassA()
  {
    return new ClassA(data);
  }

  public static ClassB modify1(ClassB y)
  {
    ClassB val = y.add(9);
    val = val.multiply(2);
    val = val.add(11);
    val = val.multiply(2);
    return val;
  }

  public static ClassB modify2(ClassB y)
  {
    ClassA m = y.makeClassA();
    m.add(9).multiply(2).add(11).multiply(2);
    return m.makeClassB();
  }

  public static void main(String[] args) {
    ClassB i2 = new ClassB(7);
    ClassB r1 = modify1(i2);
    ClassB r2 = modify2(i2);
    System.out.println("i2 = " + i2.read());
    System.out.println("r1 = " + r1.read());
    System.out.println("r2 = " + r2.read());

  }
}

Output:

i2=7
r1=86
r2=86



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial