Table of Contents
hide
Example : A java program to show no argument constructor concept.
import java.io.*;
class Construct
{
int x;
Construct()
{
x = 10;
}
public static void main(String[] args)
{
Construct obj = new Construct();
System.out.println(obj.x);
}
}
Output :
10
--------- OR ----------
import java.io.*;
class Construct
{
int x;
Construct()
{
x = 10;
System.out.println(x);
}
public static void main(String[] args)
{
new Construct();
}
}
Output :
10
--------- OR ----------
class Example
{
String nm;
Example()
{
nm= "Codershelpline";
//this.nm="Codershelpline";
}
public static void main(String[] args)
{
Example obj = new Example();
System.out.println(obj.nm);
}
}
Example : A Java program to show default as well as parameterized constructors.
import java.io.*;
class Construct
{
int x;
Construct() //Default Constructor
{
}
Construct(int p) //Parameterized Constructor
{
System.out.println(p);
}
public static void main(String[] args)
{
new Construct(); // for default constructor only
Construct obj = new Construct(10); // for both default & parameterized constructor
}
}
Example : A Java program to show parameterized constructor.
import java.io.*;
class Construct
{
int x;
Construct(int y)
{
x = y;
}
public static void main(String[] args)
{
Construct obj = new Construct(25);
System.out.println(obj.x);
}
}
Output :
25
---------- OR ------------
import java.io.*;
class Construct
{
int x;
String str;
Construct(int y, String p)
{
x = y;
str=p;
}
public static void main(String[] args)
{
Construct obj = new Construct(25,"India");
System.out.println(obj.x+obj.str);
}
}
Output :
25India
---------- OR ------------
import java.io.*;
class Construct
{
int x;
String str;
Construct(int y, String p)
{
x = y;
str=p;
}
void display()
{
System.out.println(x+" "+str);
}
public static void main(String[] args)
{
Construct obj = new Construct(25,"India");
obj.display();
}
}
Output :
25 India
Example : A java program to show constructor overloading.
class Example
{
int x;
//default constructor
public Example()
{
x = 120;
}
//parameterized constructor
public Example(int val)
{
x = val;
}
public int display()
{
return x;
}
public static void main(String args[])
{
Example obj1 = new Example();
Example obj2 = new Example(50);
System.out.println(obj1.display());
System.out.println(obj2.display());
}
}
Output :
120
50
Example : A java program to show copy constructor.
class Example
{
String name;
Example(String Str)
{
name = Str;
}
Example(Example obj3)
{
this.name = obj3.name;
//name = obj3.name;
}
void display()
{
System.out.println(name);
}
public static void main(String args[])
{
Example obj1 = new Example("Codershelpline");
obj1.display();
Example obj2 = new Example(obj1);
obj2.display();
}
}
Output :
Codershelpline
Codershelpline
0 Comments