Practical No. 10: Develop program for implementation of constructor and multiple constructor

1) Demonstrate use of at least two types of constructors.

Code:

class Const
{
int a,b;

Const(int a,int b)
{
this.a=a;
this.b=b;
}

Const()
{
a=10;
b=20;
}

public static void main( String args[]  )
{
Const c1 = new Const();

Const c2 = new Const(30,40);

System.out.println("\n\n Addition of C1 a and b: "+(c1.a+c1.b));

System.out.println("\n\n Addition of C2 a and b: "+(c2.a+c2.b));
}
}


Ouput:



2) State the Output

Code:


class T
{
int t; 
}

class Main
{
public static void main( String args[])
{
T t1 = new T();
System.out.println(t1.t);
}
}

Ouput:



3)Modify the following program to execute without error.  


Code:

class Point
{
int m_x , m_y;

public Point( int x , int y )
{
m_x = x;
m_y = y;
}

public static void main( String args[] )
{
  Point p1 = new Point();
Point p = new Point(2,3);

System.out.println("X"+p.m_x);
System.out.println("Y"+p.m_y);
System.out.println("X"+p1.m_x);
System.out.println("Y"+p1.m_y);
}
}


Ouput:
class Point
{
int m_x , m_y;

public Point( int x , int y )
{
m_x = x;
m_y = y;
}
Point()
{
m_x = 10;
m_y = 20;
}

public static void main( String args[] )
{
  Point p1 = new Point();
Point p = new Point(2,3);

System.out.println("X"+p.m_x);
System.out.println("Y"+p.m_y);
System.out.println("X"+p1.m_x);
System.out.println("Y"+p1.m_y);
}
}

4) Program to perform addition of two complex numbers.

Code:



//a+bi

class Complex
{
int a,b;

Complex(int a, int b)
{
this.a = a;
this.b = b;
}

Complex()
{
a = 10;
b = 20;
}

public static void main( String args[] )
{
Complex c1 = new Complex(10,10);
Complex c2 = new Complex();
Complex c3 = new Complex();

c3.a = c1.a + c2.a;
c3.b = c1.b + c2.b;

System.out.print("\n\n 1st Complex Number: ");
display(c1.a,c1.b);

System.out.print("\n\n 2nd Complex Number: ");
display(c2.a,c2.b);

System.out.print("\n\n Complex number Addition: ");
display(c3.a,c3.b);
}

static void display(int a,int b)
{
    if(b > 0)
      System.out.println(a + " + " + b + "i" );
    else
System.out.println( a + "  " + b + "i" );
}
}


Ouput:




Previous
Next Post »