Newer Version Available
Using Constructors
A constructor is code that is invoked when an object is created from the class blueprint. You do not need to write a constructor for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.
The syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return type and it is not inherited by the object created from it.
1public class TestObject {
2
3 // The no argument constructor
4 public TestObject() {
5 // more code here
6 }
7}1TestObject myTest = new TestObject();If you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments. If you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must include one in your code. Once you create a constructor for a class, you no longer have access to the default, no-argument public constructor. You must create your own.
1public class TestObject2 {
2
3private static final Integer DEFAULT_SIZE = 10;
4
5Integer size;
6
7 //Constructor with no arguments
8 public TestObject2() {
9 this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor
10 }
11
12 // Constructor with one argument
13 public TestObject2(Integer ObjectSize) {
14 size = ObjectSize;
15 }
16}1TestObject2 myObject1 = new TestObject2(42);
2 TestObject2 myObject2 = new TestObject2();1public class Leads {
2
3 // First a no-argument constructor
4 public Leads () {}
5
6 // A constructor with one argument
7 public Leads (Boolean call) {}
8
9 // A constructor with two arguments
10 public Leads (String email, Boolean call) {}
11
12 // Though this constructor has the same arguments as the
13 // one above, they are in a different order, so this is legal
14 public Leads (Boolean call, String email) {}
15}When you define a new class, you are defining a new data type. You can use class name in any place you can use other data type names, such as String, Boolean, or Account. If you define a variable whose type is a class, any object you assign to it must be an instance of that class or subclass.