Java4teachus

Friday, April 19, 2019

Object Parameterized Constructor in Java

Object Parameterized constructor 

A Constructor is said to be object parameterized if &only if it always takes object(s)as parameters. The Purpose of object into another object where object belongs to same type.

Object-Parameterized-Constructor.jpeg

Syntax :-

class <ClassName>
{
  ---------
<ClassName>(<ClassName> Obj1, <ClassName> Obj2.....<ClassName> Objn)
{
Block Of Statement's
}
}

Q.  Write a java program which illustrate concept  of default constructor, Overload constructor & Object parameterized constructor.

Program :-

Class Test
{
int a,b;
Test ( )
{
Sop("Test-Default Constructor");
a=1;
b=2;
Sop("val of a="+a);
Sop("val of b="+b);
}
Test (int x)
{
Sop("Test-spc");
a=x;
Sop("value of a="+a);
}
Test(int x, int y)
{
Sop("Test....Dpc");
a=x;
b=y;
Sop("val of a="+a);
Sop("val of b="+b);
}
Test(Test x)
{
Sop("Test-single-opc");
a=x.a;
b=y.b;
Sop("val of a="+a);
Sop("val of b="+b);
}
Test(Test x1 Test x2)
{
Sop("Test....double-opc");
a=x1.a + x2.a;
b=x1.b + x2.b;
Sop("val of a="+a);
Sop("val of b="+b);
}
}
Class Test Demo
{
Public static void main(String args[])
{
Test t1= new Test ();
Test t2= new Test (10,20);
Test t3 = new Test (1000);
Test t4 = new Test (t,2);
Test t5 = new Test(t1,t2);
}
}

Q. What a Java program which will containing of two objects and where each object contain 2 string vales by using Object Parameterized  Constructor  in Java.

program :-

class Lucky
{
String a,b;
Lucky(String x, String y)
{
a=x;
b=y;
System.out.println("value of a="+a);
System.out.println("value of b="+b);
}
Lucky(Lucky m1, Lucky m2)
{
a=m1.a.+m2.a;
b=m1.b+m2.b;
}
}
class LuckyJava
{
public static void main(String args[])
{
Lucky l=new Lucky("Lucky","Java");
Lucky l1=new Lucky("Java","James Gosling");
Lucky l3=new Lucky("l","l1");
}
}

Interview Points:-

  • For each & every class of java by default contains only one constructor also known as  "System Defined Default Constructor". which is provided by the "Java Environment" during compile time and it is executed by JVM at Run time whose values is to be placed default.
  • Programatically in java a class can contain two types of constructors .
  1. Single default constructor 
  2. multiple parameterized constructor (Overloaded Constructor in Java)
  • In real world  before using any class we need to know that profile of a class (Data Members, Methods, constructors). If we want see the profile of any class then we use one tool called "Javap". 
  • Syntax:-  javap FullyQualifiedName of a class/interface;
  • javap tools to be applied only on .class file which was generated after compiltion process.

No comments:

Post a Comment

Thanks for visiting my site..