Friday, April 12, 2019

this operator in java

code:


class cl {

public double a,b;

// A normal parametrized constructor
public cl(int a,int b) {
this.a = a;
this.b = b;
}

// copy constructor
cl(cl c) {
System.out.println("Copy constructor called");
a = c.a;
b = c.b;
}



void f()
{
    System.out.println(a+" "+b);
}
}

public class Main {

public static void main(String[] args) {
cl c1 = new cl(10, 15);

// Following involves a copy constructor call
cl c2 = new cl(c1);
c1.f();
c2.f();
System.out.println("xxxxxxxxxxxxx");
c1.a=5;
c1.f();
c2.f();

// Note that following doesn't involve a copy constructor call as
// non-primitive variables are just references.
cl c3 = c2;
System.out.println("xxxxxxxxxxxxx");
c3.f();
c2.f();
c1.f();
System.out.println("xxxxxxxxxxxxx");
c2.a=6;
c1.f();
c2.f();
c3.f();
System.out.println("xxxxxxxxxxxxx");
        c3.a=7;
c1.f();
c2.f();
c3.f();
System.out.println("xxxxxxxxxxxxx");
        c1.a=8;
c1.f();
c2.f();
c3.f();

}
}


output::
$javac Main.java
$java -Xmx128M -Xms16M Main
Copy constructor called
10.0 15.0
10.0 15.0
xxxxxxxxxxxxx
5.0 15.0
10.0 15.0
xxxxxxxxxxxxx
10.0 15.0
10.0 15.0
5.0 15.0
xxxxxxxxxxxxx
5.0 15.0
6.0 15.0
6.0 15.0
xxxxxxxxxxxxx
5.0 15.0
7.0 15.0
7.0 15.0
xxxxxxxxxxxxx
8.0 15.0
7.0 15.0
7.0 15.0

No comments:

Post a Comment