You are on page 1of 4

class Complex class MyClass Constructor:

{ { is a special kind of method called


private int Real; public static void Main() implicitly when creating object
private int Imag; { * has the same name of the class
public void SetR(Complex this, int r) Complex cpl1, cpl2; * has no return type, even void
public void SetR(int r) * public (except in singleton D.P)
{ this.Real = r; } cpl1 = new Complex();
public void SetI(int i) Real=7 Real=0
{ this.Imag = i; } cpl2 = new Complex(); Imag=0 Imag=0
public int GetR()
{ return this.Real; } cpl1.SetR(7);
public int GetI() cpl1.SetI(12);
{ return this.Imag; } Heap
public void Print() cpl2.SetR(18);
{ cpl2.SetI(8);
Console.WriteLine($"Real = {Real}");
Console.WriteLine($"Imag = {Imag}"); cpl1.Print(); method overloading:
} }
//Default Constructor } More than one method, having the
public Complex() same name and different in parameter
{ Real = Imag = 0 ;} implemented in the same class
//Parametrized Constructor
public Complex(int m)
{ Real = Imag = m;} method signature = method name +
public Complex(int r, int i) parameter list
{ Real = r; Imag = i; } SetR
this r
}
Creating Object: Main
1) Declaration cpl1 cpl2
2) Creation
a) Allocate (new) Stack
b) Initialize (constructor)
class Complex class MyClass
{ {
private int Real; public static void Main()
private int Imag; {
public void SetR(int r) Complex cpl1, cpl2;
{ this.Real = r; }
public void SetI(int i) cpl1 = new Complex(7, 12); 1) allocate
{ this.Imag = i; } 2) cpl1.Complex(7, 12);
cpl2 = new Complex(18); Real=7 Real=18
public int GetR()
Imag=12 Imag=18
{ return this.Real; }
public int GetI()
{ return this.Imag; }
public void Print() cpl1.Print();
{ }
Console.WriteLine($"Real = {Real}"); }
Console.WriteLine($"Imag = {Imag}");
}
//Default Constructor Destructor:
public Complex() is a method called implicitly when removing object from memory
{ Real = Imag = 0 ;} * has the same name of the class preceeding with ~
//Parametrized Constructor * has no return type even void
public Complex(int m) * has no parameter list
{ Real = Imag = m;} * public
public Complex(int r, int i)
{ Real = r; Imag = i; } 7 12
} this r i

Creating Object:
1) Declaration cpl1 cpl2
2) Creation
a) Allocate (new)
b) Initialize (constructor)
Creating Object

Default Constructor Parametrized Constructor

The required parametrized Constructor


is
MUST EXIST
Yes there any No
Default Constructor

is
Use the default constructor Yes No
there any
Parametrized constructor

Generate compile error Auto generate a default


constructor initializing all the
member with 0, false or null
Destructing Object
Removing object is done by the gabage collector.

Garbage collector, remove un-referenced object

Garbage collector:
1) Identify the Un-Referenced Object
2) Remove Un-Referenced Object
a) Execute destructor if exist
b) De-Allocate

obj

You might also like