Write
a program in Java to develop overloaded constructor. Also develop the copy
constructor to create a new object with the state of the existing object.
public class OverloadCopyConst
{
int n;
OverloadCopyConst()
{
System.out.println("Default Constructor");
}
OverloadCopyConst(int x, int y)
{
System.out.println("Addition is "+(x+y));
}
OverloadCopyConst(int a)
{
n=a;
System.out.println("Number is "+n);
int i,j,flag;
for(i=1;i<=n;i++)
{
flag=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag++;
break;
}
}
if(flag==0)
{
System.out.println("Prime
is "+i);
}
}
}
OverloadCopyConst(OverloadCopyConst cp, int a)
{
n=cp.n;
int max;
max=a>n?a:n;
System.out.println("Maximum number is "+max);
}
public static void main(String arg[])
{
OverloadCopyConst cp1=new OverloadCopyConst(5,6);
OverloadCopyConst cp2=new OverloadCopyConst(5);
OverloadCopyConst cp3=new OverloadCopyConst(cp2,5);
}
OUTPUT:-
Develop
minimum 4 program based on variation in methods i.e. passing by value, passing
by reference, returning values and returning objects from methods
1.
passing
by value
class PBV
{
int i;
void set_data(int a)
{
i=a;
}
void display()
{
System.out.print("i : " + i);
}
}
public class Example
{
public static void main(String[] args)
{
PBV obj = new PBV();
obj.set_data(5); //Pass by Value
obj.display();
}
OUTPUT:-
i : 5
2. passing by reference
class PBR
{
int i;
void set_data(PBR o)
{
i = o.i;
}
void display()
{
System.out.print("i : " + i);
}
}
public class Example
{
public static void main(String[] args)
{
PBR obj1 = new PBR();
PBR obj2 = new PBR();
obj1.i=7;
obj2.set_data(obj1); //Pass by Reference
obj2.display();
}
OUTPUT:-
i : 7
3. Returning values
class RBV
{
int i;
void set_data(int a)
{
i=a;
}
int incrByOne()
{
i++;
return (i);
}
}
public class Example
{
public static void main(String[] args)
{
RBV obj1 = new RBV();
obj1.set_data(5); //Pass by Value
int value = obj1.incrByOne(); // Return
by Value
System.out.println("i : " +
value);
}
OUTPUT:-
i : 6
4. Returning objects
class RBR
{
int i;
RBR Copy()
{
RBR temp = new RBR();
temp.i = i;
return temp;
}
void display()
{
System.out.println("i : "+ i);
}
}
public class Example
{
public static void main(String[] args)
{
RBR obj1 = new RBR();
obj1.i=7;
RBR obj2 = obj1.Copy(); //Return by
Reference
obj1.display();
obj2.display();
}
OUTPUT:-
i : 7
i : 7
Comments
Post a Comment