Page 358 - CITS - Computer Software Application -TT
P. 358

COMPUTER SOFTWARE APPLICATION - CITS



           1  Java No-Arg Constructors

           Similar to methods, a Java constructor may or may not have any parameters (arguments).
           If a constructor does not accept any parameters, it is known as a no-argument constructor.
           2  Java Parameterized Constructor
           A Java constructor can also accept one or more parameters. Such constructors are known as parameterized
           constructors (constructors with parameters).
           3  Java Default Constructor
           If we do not create any constructor, the Java compiler automatically creates a no-arg constructor during the
           execution of the program.
           Important Notes on Java Constructors
           •  Constructors are invoked implicitly when you instantiate objects.
           •  The two rules for creating a constructor are:
              1  The name of the constructor should be the same as the class.

              2  A Java constructor must not have a return type.
           •  If a class doesn’t have a constructor, the Java compiler automatically creates a default constructor during run-
              time. The default constructor initializes instance variables with default values. For example, the int variable will
              be initialized to 0
           •  Constructor types:
              No-Arg Constructor - a constructor that does not accept any arguments
              Parameterized constructor - a constructor that accepts arguments

              Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly
              defined.
           •  A constructor cannot be abstract or static or final.

           •  A constructor can be overloaded but can not be overridden.
           Constructors Overloading in Java
           Similar to Java method overloading, we can also create two or more constructors with different parameters. This
           is called constructor overloading.
           Example: Java Constructor Overloading
           class Main {
             String language;
             // constructor with no parameter

             Main() {
               this.language = “Java”;
             }
             // constructor with a single parameter
             Main(String language) {

               this.language = language;
             }
             public void getName() {
               System.out.println(“Programming Language: “ + this.language);

             }



                                                           345

                             CITS : IT&ITES - Computer Software Application - Lesson 94 - 100
   353   354   355   356   357   358   359   360   361   362   363