fork download
  1. class Student {
  2.  
  3. // Data members
  4. int rollNo;
  5. String name;
  6. double marks;
  7.  
  8. // 1. Default Constructor
  9. Student() {
  10. rollNo = 30;
  11. name = "Vaishnavi";
  12. marks = 85.3;
  13. }
  14.  
  15. // 2. Parameterized Constructor
  16. // Parameter names are different from data member names
  17. Student(int r, String n, double m) {
  18. rollNo = r;
  19. name = n;
  20. marks = m;
  21. }
  22.  
  23. // 3. Constructor Overloading
  24. Student(int r, String n) {
  25. rollNo = r;
  26. name = n;
  27. marks = 0.0;
  28. }
  29.  
  30. // 4. Method Overloading - No parameter
  31. void display() {
  32. System.out.println("Roll No : " + rollNo);
  33. System.out.println("Name : " + name);
  34. System.out.println("Marks : " + marks);
  35. }
  36.  
  37. // Method Overloading - One parameter
  38. void display(String message) {
  39. System.out.println(message);
  40. System.out.println("Roll No : " + rollNo);
  41. System.out.println("Name : " + name);
  42. }
  43.  
  44. // Method Overloading - Two parameters
  45. void display(String message, boolean showMarks) {
  46. System.out.println(message);
  47. System.out.println("Roll No : " + rollNo);
  48. System.out.println("Name : " + name);
  49.  
  50. if (showMarks) {
  51. System.out.println("Marks : " + marks);
  52. }
  53. }
  54. }
  55.  
  56. public class Main {
  57.  
  58. public static void main(String[] args) {
  59.  
  60. // Object using default constructor
  61. Student s1 = new Student();
  62.  
  63. // Object using parameterized constructor
  64. Student s2 = new Student(31, "vaidehi", 83.5);
  65.  
  66. // Object using overloaded constructor
  67. Student s3 = new Student(32, "ravee");
  68.  
  69. System.out.println("===== DEFAULT CONSTRUCTOR =====");
  70. s1.display();
  71.  
  72. System.out.println("\n===== PARAMETERIZED CONSTRUCTOR =====");
  73. s2.display();
  74.  
  75. System.out.println("\n===== CONSTRUCTOR OVERLOADING =====");
  76. s3.display();
  77.  
  78. System.out.println("\n===== METHOD OVERLOADING =====");
  79.  
  80. s2.display();
  81.  
  82. System.out.println();
  83.  
  84. s2.display("Student Details:");
  85.  
  86. System.out.println();
  87.  
  88. s2.display("Complete Student Details:", true);
  89. }
  90. }
Success #stdin #stdout 0.15s 55780KB
stdin
Standard input is empty
stdout
===== DEFAULT CONSTRUCTOR =====
Roll No : 30
Name    : Vaishnavi
Marks   : 85.3

===== PARAMETERIZED CONSTRUCTOR =====
Roll No : 31
Name    : vaidehi
Marks   : 83.5

===== CONSTRUCTOR OVERLOADING =====
Roll No : 32
Name    : ravee
Marks   : 0.0

===== METHOD OVERLOADING =====
Roll No : 31
Name    : vaidehi
Marks   : 83.5

Student Details:
Roll No : 31
Name    : vaidehi

Complete Student Details:
Roll No : 31
Name    : vaidehi
Marks   : 83.5