Aug 18, 2014

17. Constructors


When a new object is initialized it will use the compiler default constructor. Should we write constructors of our own, then it will use one of the constructors that we wrote. Constructors have to have the same name as class and thus the convention is they will start with a capital letter. This sets them apart from other methods.




Should we write constructor(s), we will have to write the no-argument constructor, should we wish that to be one way to create our class instance. At construction time, values should be initialized. In the first case, all values are set to their default.


 // *** 1. Start (Constructor 1)
 public Ex17() {
  a = 1;
  b = 2;
  s = "Hello World!";
 }
 // *** 1. End



The second constructor has one integer in parameter list. Thus, only 1-integer is set to a non-default value.


 // *** 2. Start (Constructor 2)
 public Ex17(int a) {
  this.a = a;
  b = 2;
  s = "Hello World!";
 }
 // *** 2. End



The third constructor, in this example, has two integers in the argument list. It sets the two integer instances to the argument values.


 // *** 3. Start (Constructor 3)
 public Ex17(int a, int b) {
  this.a = a;
  this.b = b;
  s = "Hello World!";
 }
 // *** 3. End



The fourth constructor has an integer and String in the argument list. It sets two of the three instance variables to the argument values.


 // *** 4. Start (Constructor 4)
 public Ex17(int a, String s) {
  this.a = a;
  b = 2;
  this.s = s;
 }
 // *** 4. End



In constructor 5, all three instance values are set to the local variables in the argument list.


 // *** 5. Start (Constructor 5)
 public Ex17(int a, int b, String s) {
  this.a = a;
  this.b = b;
  this.s = s;
 }
 // *** 5. End



package com.javaAndroid.ex17;

public class Ex17 {
 int a,b;
 String s;
 // *** 1. Start (Constructor 1)
 public Ex17() {
  a = 1;
  b = 2;
  s = "Hello World!";
 }
 // *** 1. End
 // *** 2. Start (Constructor 2)
 public Ex17(int a) {
  this.a = a;
  b = 2;
  s = "Hello World!";
 }
 // *** 2. End
 // *** 3. Start (Constructor 3)
 public Ex17(int a, int b) {
  this.a = a;
  this.b = b;
  s = "Hello World!";
 }
 // *** 3. End
 // *** 4. Start (Constructor 4)
 public Ex17(int a, String s) {
  this.a = a;
  b = 2;
  this.s = s;
 }
 // *** 4. End
 // *** 5. Start (Constructor 5)
 public Ex17(int a, int b, String s) {
  this.a = a;
  this.b = b;
  this.s = s;
 }
 // *** 5. End
 public static void main(String[] args) {
  Ex17 o1 = new Ex17();
  System.out.printf("a = %d, b = %d, s = %s\n",o1.a,o1.b,o1.s);
  Ex17 o2 = new Ex17(3);
  System.out.printf("a = %d, b = %d, s = %s\n",o2.a,o2.b,o2.s);
  Ex17 o3 = new Ex17(5,6);
  System.out.printf("a = %d, b = %d, s = %s\n",o3.a,o3.b,o3.s);
  Ex17 o4 = new Ex17(7,"Java!");
  System.out.printf("a = %d, b = %d, s = %s\n",o4.a,o4.b,o4.s);
  Ex17 o5 = new Ex17(9,8,"jMonkey Engine 3");
  System.out.printf("a = %d, b = %d, s = %s\n",o5.a,o5.b,o5.s);
 }
}



No comments:

Post a Comment