Saturday, 16 February 2013

Posted by Prasad KM | 01:36 Categories:
 Constructor Question


1. what is the meaning of Static constructor ?

A static constructor initializes static fields. It runs at an indeterminate time before those fields are used. Microsoft's documentation and many developers warn that static constructors on a type impose a substantial overhead.
2. What is the meaning of  private constructor   ?

If I remember correctly (don't actually use either of these much myself), a private constructor means an instance of the object can only be created by itself. In other words you couldn't create an instance of Object1 from Object2, only from inside Object1. While I'm sure there's a use for this I've never come across it in my job.

As for final methods, I believe that's just a case where you don't want the method to be overridden. For example maybe you have a class that does a calculation on some financial numbers and you don't want anyone overridding your method in a subclass you could declare that method final.

I'm just coming up with this from memory as I have said in my job I've never actually used either. But that could be just because of the specific project I work on. Someone else might be able to correct me or even give a real world example.


3. What is the meaning of Singleton Design pattern ?

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.

class Singleton
{
 private static Singleton instance;
 private Singleton()
 {
  ...
 }

 public static synchronized Singleton getInstance()
 {
  if (instance == null)
   instance = new Singleton();

  return instance;
 }
 ...
 public void doSomething()
 {
  ... 
 }
}
 
4. what is the use of private constructor and why to make constructor as private?

  1. The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
  2. A utility class, that only contains static methods.
5. what is the use of  constructor ?

Constructor are used for initialization of member variables.Constructor are automatically invoked when the object is created.Constructor doesn't have any return type not even void.Constructor have the same name as the class name.We can't call the constructor explicitly.

class A()
{
public int x;
public int y;
public int z;
A()
{
x=10;
y=20
}
public void Add()
{
z=x+y;
}
}
private void button1_click()
{
A a=new A();
int sum;
sum=a.Add();
MessageBox.Show(sum.toString());
}

0 comments:

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube