Example 1: Java program to demonstrate the use of constructor
KW.java
class KW
{
    int i=0;
    public KW()
    {
        i=i+1;
        System.out.println(i);
    }
    public static void main(String args[])
    {
        KW k=new KW();
        KW k1=new KW();
        KW k2=new KW();
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW 1 1 1 kodingwindow@kw:~$
Example 2: Java program to demonstrate the use of constructor
KW.java
class KW
{
    int a=20;
    KW(int a)
    {
        a=a;
        System.out.println(a);
    }
    public static void main(String args[])
    {
        KW k=new KW(10);
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW 10 kodingwindow@kw:~$
Example 3: Java program to demonstrate the use of constructor
KW.java
class KW
{
    int a;
    KW()
    {
        this(30);
    }
    KW(int a)
    {
        this.a=a;
        System.out.println(a);
    }
    public static void main(String args[])
    {
        KW k1=new KW();
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW 30 kodingwindow@kw:~$
Example 4: Java program to demonstrate the use of constructor
KW.java
class Shape
{
    public Shape()
    {
        System.out.println("1");
        new Shape(10);
        System.out.println("2");
    }
    public Shape(int side)
    {
        System.out.println("3");
        new Shape(10,20);
        System.out.println("4");
    }
    public Shape(int width, int breadth)
    {
        System.out.println("5");
    }
}
class KW
{
    public static void main(String args[])
    {
        Shape s=new Shape();
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW 1 3 5 4 2 kodingwindow@kw:~$
Advertisement