Sunday, November 20, 2011

What is a constructor and difference between this and super


A constructor is a special type of function that gets called every time you initialize a class, constructor has the same name as class name. Constructor has no return type not even void. We can pass the parameters to the constructor.

-this() is used to invoke a constructor of the same class.

-super() is used to invoke a super class constructor.

Constructor is called immediately after the object is created before the new operator completes.

For example, say you have this class called Person:
class Person
{
public Person ()
{
Console.WriteLine("We're making a new person");
}
}

Now you can create a new object of type Person, like this:
Person Tim= new person();

The program will write the line "We're making a new person" to the screen.

  • Constructor can use the access modifiers public, protected, private or have no access modifier
  • Constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp
  • Constructor can be overloaded, we cannot override.
  • You cannot use this() and Super() in the same constructor.
  • You can not have both super() and this() invocation in the same constructor.
  • Either super() or this() should be the first statement in the constructor.

Stumble
Delicious
Technorati
Twitter

0 Comments:

Post a Comment