Saturday, January 4, 2020

Using Java Constructors An Easy How-To Guide

A Java constructor creates a new instance of an already-defined object. This article discusses how to use Java constructor methods to create a Person object. Note: You need to create two files in the same folder for this example: Person.java defines the Person class, and PersonExample.java contains the main method that creates Person objects. The Constructor Method Lets 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. Weve 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 similar to any other 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, our constructor method does nothing at all, and its 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 didnt include a constructor method in our Person class (in Java you can define a class without one), then the fields would have no values — and we certainly want our person to have a name and address as well as other characteristics.  If you think theres 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, to ensure that a constructor method is useful, we would design it to expect 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 constructor method now expects the values of four strings to be passed to it. They are then used to set the initial state of the object. Weve 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 Main St., DDavidson); dave.displayPersonDetails(); } } Heres what we did: To create the new instance of the Person object, we first define a variable of type Person that will hold the object. In this example, weve called it dave.On the other side of the equals sign, we call the constructor method of our Person class and pass it four string values. Our constructor method will take those four values and set the initial state of the Person object to be: firstName Dave, lastName Davidson, address 12 Main St, username DDavidson. Notice how weve switched to the Java main class to call the Person object. When you work with objects, programs will span multiple .java files. Make sure you save them in the same folder. To compile and run the program, simply compile and run the Java main class file (i.e., PersonExample.java). The Java compiler is smart enough to realize that you want to compile the Person.java file as well because it can see that you have used it in the PersonExample class. Naming of Parameters The Java compiler gets confused if the parameters of the constructor method have the same names as the private fields. In this example, you can see that we have distinguished between them by prefixing the parameters with the word person. Its 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. Its a question of programming style, but this method helps us define constructor parameters without having to use multiple names. More Than One Constructor Method When designing your object classes, you are not limited to using only one constructor method. 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 the parameters must differ. Imagine that at the time we create the Person object, we might not know the username. Lets 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 expects only 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 Main St., DDavidson); Person jim new Person(Jim,Davidson, 15 Kings Road); dave.displayPersonDetails(); jim.displayPersonDetails(); } } Person dave will be created with a firstName, lastName, address, and username. Person jim, however, will not get a username, i.e. the username will be the empty string: username . A Quick Recap Constructor methods are called only when a new instance of an object is created. They: Must have the same name as the classDo not return a valueCan have none, one, or many parametersCan number more than one as long as each constructor method has a different set of parametersCan have parameter names the same as the private fields as long as the this keyword is usedAre called using the new keyword

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.