Class and object
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.
Box b1;//Reference variable,can not create memory
b1 is called a reference variable (not object)
now b1 is null
Box b2 = new Box();// object b2 of class BOX is instantiated and create memory on Heap
now b2 points box object
Box b3 = new Box();
b3.length = 10;
b3.width = 20;
b1 = b3; //an object is assigned to a reference variable
now both b1 and b3 both points to same memory location..if any one updated then another one automatically updated.
Sample code
Sample code
namespace ConsoleApplicationdemo {
class Program {
static void Main(string[] args) {
Box b1; //Reference variable,not create memory
Box b2 = new Box(); // object b2 of class BOX is instantiated and create memory on Heap
Console.WriteLine("b2 object length:{0}", b2.length); //by default vale
Console.WriteLine("b2 object width:{0}", b2.width); //by default vale
Box b3 = new Box();
b3.length = 10;
b3.width = 20;
Console.WriteLine("b3 object length:{0}", b3.length);
Console.WriteLine("b3 object width:{0}", b3.width);
b1 = b3; //an object is assigned to a reference variable
//now reference variable works like an object
//both b3 and b1 points to same memory location if any one updated then another one automatically updated
Console.WriteLine("after assigning b3,the b1 object length:{0}", b1.length);
Console.WriteLine("after assigning b3,the b1 object width:{0}", b1.width);
///////////////////////////modify b3
b3.length = 45;
b3.width = 55;
Console.WriteLine("Modified b3 object length:{0}", b3.length);
Console.WriteLine("Modified b3 object width:{0}", b3.width);
Console.WriteLine("after modify b3,the b1 object length:{0}", b1.length);
Console.WriteLine("after modify b3,the b1 object width:{0}", b1.width);
///////////////////////////modify b1
b1.length = 70;
b1.width = 80;
Console.WriteLine("Modified b1 object length:{0}", b1.length);
Console.WriteLine("Modified b1 object width:{0}", b1.width);
Console.WriteLine("after modify b1,the b3 object length:{0}", b3.length);
Console.WriteLine("after modify b1,the b3 object width:{0}", b3.width);
Console.ReadKey();
}
}
class Box {
public int length;
public int width;
int height; // by default private ,any object of class cant access this data field
}
}
Output
b2 object length:0
b2 object length:0
b2 object width:0
b3 object length:10
b3 object width:20
after assigning b3,the b1 object length:10
after assigning b3,the b1 object width:20
Modified b3 object length:45
Modified b3 object width:55
after modify b3,the b1 object length:45
after modify b3,the b1 object width :55
Modified b1 object length:70"
Modified b1 object width:80
after modify b1,the b3 object length:70
after modify b1,the b3 object width:80
