开发者

Declaring class instance and its initialization

开发者 https://www.devze.com 2023-01-20 01:38 出处:网络
If I create the variable with type of a class, what is the actual va开发者_运维问答lue I will initialize it with? I mean - the int is initialized with value of that type that is number. But in the ter

If I create the variable with type of a class, what is the actual va开发者_运维问答lue I will initialize it with? I mean - the int is initialized with value of that type that is number. But in the terms of technical precision, what happens when I create new instance of class?

class a
{
}
class b
{
  a InstanceOfA;
    InstanceOfA=new ();  //which what I initialize the variable?
}

Hopefully you will get my point, thanks


You want to create a new instance of class a. Here's an example, with the classes renamed to ease reading.

class MyClassA {
}

class MyClassB {
    MyClassA a = new MyClassA();
}

If your class a requires some initialization, implement a constructor for it:

class MyClassA {
    public MyClassA() {
        // this constructor has no parameters
        Initialize();
    }

    public MyClassA(int theValue) {
         // another constructor, but this one takes a value
         Initialize(theValue);
    }
}

class MyClassB {
    MyClassA a = new MyClassA(42);
}


You're probably after something like this:

public class A
{
}

public class B
{
    public static void Main(string[] args)
    {
      // Here you're declaring a variable named "a" of type A - it's uninitialized.
      A a;
      // Here you're invoking the default constructor of A - it's now initialized.
      a = new A();
    }
}


Member variables of a class is initialised with the default value of their type. For a reference type this means that it's initialised to null.

To create an instance of the class, you simply use the class name:

InstanceOfA = new a();


I'm not sure I got what you're asking, but if I did-
When you initialize a class, it's name is assigned it's reference address.
So when you write

InstanceOfA = new a();

InstanceOfA gets an address in memory (on the heap..) for an object of type a.

0

精彩评论

暂无评论...
验证码 换一张
取 消