Page 271 - PowerPoint Presentation
P. 271

CAVITE STATE UNIVERSITY
                               TRECE MARTIRES CITY CAMPUS
                               Department of Information Technology            DCIT 111 - Advanced Programming

                  public class TestStudent {
                  public static void main (String[]args) {

                        Student Student1 = new Student();   // creating
                        Student Student2 = new Student();   // objects

                        Student1.displayCreation();   // displaying the values
                        Student2.displayCreation();   // of the object                     OUTPUT:
                  }                                                                        0 null
                  }                                                                        0 null

               Explanation: In the above class, you are not creating any constructor so the compiler provides
               you a default constructor. Here 0 and null values are provided by default constructor.
               NOTE: CONTRUCTOR NAME MUST BE THE SAME AS ITS CLASS NAME. JUST ADD ().

               Java Parameterized Constructor
                       A constructor which has a specific number of parameters is called a parameterized
               constructor.

               Why use the parameterized constructor?
                       The  parameterized  constructor  is  used  to  provide  different  values  to  the  distinct
               objects. However, you can provide the same values also.
               Example of Parameterized Constructor

                  // Java program to demonstrate the use of parameterized constructor
                  class Student {      // this is the class
                        int ID;
                        String Name;

                        Student (int id, String name) {  // creating a parameterized constructor
                               ID = id;

                               Name = name;
                        }

                        void display(){  // method to display information
                        System.out.println(ID + “ “ + Name);
                        }
                  public class TestStudent {   // main class (TestStudent.java)
                        public static void main(String[]args){
                        Student Student1 = new Student(111, “Chan”);
                        Student1.display();
                  }                           // no need to separate Student Student1 = new Student();
                  }                                  // from Student1 = (111, “Chan”);

               In using constructors, the code is more compressed to smaller portion than using objects and
               classes.











                                                                                                            47
   266   267   268   269   270   271   272   273   274   275   276