Classes

Constructors

One of the most important things in the design of the classes are the constructors. But wait, what a constructor is? Well, first of all, do you remember this line?


 MyClass class = new MyClass();
	
Well, here we are using a constructor. So, when you create a new instance and use the new keyword, you are using a constructor. In simple words, a constructor is a method used when creating a class instance.

As I said in the last section, the best for learning is coding. So let's write a constructor por the class MyClass.

 class MyClass {

 	public MyClass ( int n )
	{

		this.myField = n;

	}

 }
The only difference in declaring a method and a constructor, is that the constructor doesn't need to specify a return value. Try to specify it like coid or int, and you'll get a compilation error. If you are asking yourself where is it supposed to be used, here you have the answer: you use it when declaring a new instance, so, for example, it could be:
 int n = 78;
 MyClass class_a = new MyClass(n);
 MyClass class_b = new MyClass(89);
We are passing a integer as parameter, because we specified it in the constructor. Now I'm sure you'll be able to see clearer the situation: a constructor is a method used when there is need to initializase some elements in the current instance, and has the special feature that doesn't have a return value.

The last thing you have to remember is the this keyword, which is refering to the current instance ( remember that every instance has its own elements ). So, when you combine the this keyword with a dot, you are accessing to the element of the instance. Here, we are modifying the private myField field inside the class_b and class_b instances, so, when using the public GetResult method, we will be able to guess the return value.

Default Constructor

When you don't declare any constructor, the environment will use a default constructor for you class. So, if you don't need to initialize any elements in your class, you'll have no problems when creating instances.

Private Constructor

When you change the public keyword of the constructor with private, you are specifying yo don't want create any instances of the current class ( who could reach it? ).

 private MyClass ()
 {

 }
As you can see, there's no need of declaring any action, because it is no neccesary.