Classes

How do I declare an instance of the class?

In our previous tutorial we looked at the concept of variables. Let's have a quick refresh on how to declare variables:

public class Program { public static...

 

In our example above, we've declared a String variable named name, using the string alias.

To declare an instance of our class, we do something very similar:

public class Program
{
    public static void Main()
    {
        Person person = new Person();
    }
}

In our example above, we've declared a variable of type Person, named person.  The next part of the expression, is known as the  initializer :

new Person();

What this is telling the runtime, is that it should allocate some memory the size of an instance of the Person class, and allocate a reference to that memory location to the person variable. This particular initializer uses something known as the  default constructor for the Person type.  We'll come to constructors later in this tutorial.

Page 5 of 20