Constructor demo program
Constructor:
1.
Name same as class
name
2.
No return type
3.
Initialization
4.
Can has parameter
5.
Constructor can be overloaded
6.
Constructor called when object is created
Declaration:
class Const_Demo
{
Const_Demo(){ //constructor name must be same as class name
//
constructor body
}
Public
static void main(String[] args){
Const_Demo obj = new Const_Demo();
}
}
// program
to using constructor
package
constructordemo;
public class
ConstructorDemo {
public
ConstructorDemo() {
System.out.println("This is constructor
demo program");
}
public static void main(String[] args) {
ConstructorDemo obj = new ConstructorDemo();
}
}
Constructor also accept
overloading. Below the program constructor overloading
constructor overloading program
//constructor overloading program
package constructordemo;
public class ConstructorDemo //class name as ConstructorDemo
{
public ConstructorDemo() //constructor
initialized as ConstructorDemo
{
System.out.println("This is constructor
demo program");
}
public ConstructorDemo(int a, int b) //constructor overloading
{
int sum = a+b;
System.out.println("add of
two no. is:"+sum);
}
public ConstructorDemo(int a) //constructor overloading {
System.out.println("This is
constructor overloading body");
}
public static void main(String[] args)
{
ConstructorDemo obj1 = new
ConstructorDemo(); //constructor called by creating obj.
ConstructorDemo obj2 = new
ConstructorDemo(10,20); //constructor called by creating obj.
ConstructorDemo obj3 = new
ConstructorDemo(1); //constructor called by creating obj.
}
}
if you want to print object then what will be happen, let’s
see.
package constructordemo;
public class ConstructorDemo {
public ConstructorDemo() {
//constructor body……
}
public static void
main(String[] args) {
ConstructorDemo obj1 = new
ConstructorDemo();
System.out.println(obj1);
}
}
Output:
0 comments: