Custom Search

Saturday, March 9, 2013

Java Constructor



Java Constructor


What is a java constructor?
  • A constructor creates an Object of the class that it is in by initializing all the instance variables and creating a place in memory to hold the Object. 
  • It is always used with the keyword new and then the Class name. For instance, new String(); constructs a new String object.
  • Sometimes in a few classes you may have to initialize a few of the variables to values apart from their predefined data type specific values. 
  • If java initializes variables it would default them to their variable type specific values. For example you may want to initialize an integer variable to 10 or 20 based on a certain condition, when your class is created. 
  • In such a case you cannot hard code the value during variable declaration. such kind of code can be placed inside the constructor so that the initialization would happen when the class is instantiate


Providing Constructors for Your Classes

  • A class contains constructors that are invoked to create objects from the class blueprint. 
  • Constructor declarations look like method declarations—except that they use the name of the class and have no return type. 


For example, Bicycle has one constructor:
public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.
Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() {
    gear = 1;
    cadence = 10;
    speed = 0;
}

  • Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.
  • Both constructors could have been declared in Bicycle because they have different argument lists. 
  • As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. 



The Constructor Method
Let's start by creating a Person class that has four private fields – firstName, lastName, address, and username. These fields are private variables and together their values make up the state of an object. I've also added the simplest of constructor methods:
 public class Person {

   private String firstName;
   private String lastName;
   private String address;
   private String username;

   //The constructor method
   public Person()
   {

   }
 }

  • The constructor method is like a normal public method except that it shares the same name as the class and it cannot return a value. 
  • It can have none, one or many parameters.
  • Currently the constructor method does nothing at all and it's a good time to consider what this means for the initial state of the Person object. 
  • If we left things as they are or we didn't include a constructor method in our Person class (in Java you can define a class without one), then the fields would have no values. If you think there's a chance that your object might not be used as you expect and the fields might not be initialized when the object is created, always define them with a default value:

 public class Person {

   private String firstName = "";
   private String lastName = "";
   private String address = "";
   private String username = "";

   //The constructor method
   public Person()
   {

   }
 }
Normally for a constructor method to be useful we would design it so that it expects parameters. 
The values passed through these parameters can be used to set the values of the private fields:
 public class Person {

   private String firstName;
   private String lastName;
   private String address;
   private String username;

   // The constructor method
   public Person(String personFirstname, String personLastName, String personAddress, String personUsername)
   {
     firstName = personFirstName;
     lastName = personLastName;
     address = personAddress;
     username = personUsername;
   }

   // A method to display the state of the object to the screen
   public void displayPersonDetails()
   {
     System.out.println("Name: " + firstName + " " + lastName);
     System.out.println("Address: " + address);
     System.out.println("Username: " + username);
   }
 }

Our constructer method now expect the values of four strings to be passed to it. They are then used to set the initial state of the object. I've also added a new method called displayPersonDetails to enable us to see the state of the object after it has been created.
Calling the Constructor Method
Unlike other methods of an object the constructor method must be called using the "new" keyword:
 public class PersonExample {

   public static void main(String[] args) {

     Person dave = new Person("Dave", "Davidson", "12 Pall Mall", "DDavidson");
     dave.displayPersonDetails();

   }
 }

  • To create the new instance of the Person object we first define a variable of type Person that will hold the object. 
  • In the example it have called it dave. 
  • On the other side of the equals sign we are calling the constructor method of our Person class and passing it four string values. 
  • Our constructor method will takes those four values and set the initial state of the Person object to be: firstname = "Dave", lastname = "Davidson", address = "12 Pall Mall", username = "DDavidson".


Naming of Parameters
  • The Java compiler will get confused if the parameters of the constructor method have the same names as the private fields. 
  • In the example you can see that I have distinguished between them by prefixing the parameters with the word "person".
  •  It's worth mentioning that there is another way. 

We can use the "this" keyword instead:
   // The constructor method
   public Person(String firstName, String lastName, String address, String username)
   {
     this.firstName = firstName;
     this.lastName = lastName;
     this.address = address;
     this.username = username;

   }

  • The "this" keyword tells the Java compiler that the variable to be assigned the value is the one defined by the class, not the parameter. 
  • It's a question of programming style, but this is my preferred method of defining constructor parameters because it's easier than thinking up new names!

More Than One Constructor Method
  • When designing your object classes you are not limited to only using one constructor class. 
  • You might decide there are a couple of ways an object can be initialized. 
  • The only constraint on using more than one constructor method is that they must differ in the parameters they accept.
  • Imagine that at the time we create the Person object we might not know the username we want to give to a person.

 Let's add a new constructor method that sets the state of the Person object using only the firstname, lastname and address:
 public class Person {

   private String firstName;
   private String lastName;
   private String address;
   private String username;

   // The constructor method
   public Person(String firstName, String lastName, String address, String username)
   {
     this.firstName = firstName;
     this.lastName = lastName;
     this.address = address;
     this.username = username;
   }

   // The new constructor method
   public Person(String firstName, String lastName, String address)
   {
     this.firstName = firstName;
     this.lastName = lastName;
     this.address = address;
     this.username = "";
   }

   // A method to display the state of the object to the screen
   public void displayPersonDetails()
   {
     System.out.println("Name: " + firstName + " " + lastName);
     System.out.println("Address: " + address);
     System.out.println("Username: " + username);
   }
 }

Note that the second constructor method is also called "Person" and it also does not return a value. The only difference between it and the first constructor method is the parameters – this time it is only expecting three string values: firstName, lastName and address.
We can now create Person objects in two different ways:
 public class PersonExample {

   public static void main(String[] args) {

     Person dave = new Person("Dave", "Davidson", "12 Pall Mall", "DDavidson");
     Person jim = new Person("Jim","Davidson", "15 Kings Road");
     dave.displayPersonDetails();
     jim.displayPersonDetails();
   }

 }

dave will be created with a state of: firstname = "Dave", lastname = "Davidson", address = "12 Pall Mall", username = "DDavidson". Jim will not get a username and instead will have a state of: firstname = "Jim", lastname = "Davidson", address = "15 Kings Road", username = "".

No comments:

Post a Comment