• Source
    1. /*
    2.  
    3.  
    4. Date : 11 November 2013
    5. Author : Shivam Tiwari
    6. Organization : http://mycodedock.blogspot.in/
    7. Description : Demonstrating constructors in Java
    8.  
    9.  
    10. */
    11.  
    12. //Making the class
    13. class UselessClass{
    14.  
    15. //declaring variables
    16. int x;
    17. double y;
    18.  
    19. //declring first constructor
    20. //it can be used to set the value of variables while creating objects
    21. UselessClass(int a, double b){
    22. x = a;
    23. y = b;
    24. }
    25.  
    26. //declaring second constructor
    27. //it can be used to create objects with zero values set in variables
    28. UselessClass(){
    29. x = 0;
    30. y = 0;
    31. }
    32. }
    33. public class Main
    34. {
    35. public static void main (String[] args) throws java.lang.Exception
    36. {
    37. //creating an object using first constructor
    38. UselessClass obj1 = new UselessClass(2,4.567);
    39.  
    40. //creating an objecct using second constructor
    41. UselessClass obj2 = new UselessClass();
    42.  
    43. //Lets check by printing values
    44. System.out.println("Printing from object that was created using first constructor");
    45. System.out.println("int x = " + obj1.x);
    46. System.out.println("double y = " + obj1.y);
    47.  
    48. System.out.println("Printing from object that was created using second constructor");
    49. System.out.println("int x = " + obj2.x);
    50. System.out.println("double y = " + obj2.y);
    51. }
    52. }