Summary: An introduction to Java syntax covering simple Java expressions and the declaration of concrete classes and methods.
This module contains an assortment of topics covering Java syntax. It is not intended to be a complete tutorial.
A constructor can be thought of as a specialized method of a class that creates (instantiates) an instance of the class and performs any initialization tasks needed for that instantiation. The sytnax for a constructor is similar but not identical to a normal method and adheres to the following rules:
public Person { private String _name; public Person(String name) { _name = name; } }The above code defines a public class called Person with a public constructor that initializes the _name field.
To use a constructor to instantiate an instance of a class, we use the new keyword combined with an invocation of the constructor, which is simply its name and input parameters. new tells the Java runtime engine to create a new object based on the specified class and constructor. If the constructor takes input parameters, they are specified just as in any method. If the resultant object instance is to be referenced by a variable, then the type of the newly created object must be of the same type as the variable. (Note that the converse is not necessarily true!). Also, note that an object instance does not have to be assigned to a variable to be used.
Person me = new Person("Stephen");The above code instantiates a new Person object where _namefield has the value "Stephen".