Question on Classes

Reply Forum
Forum postBrant Williams @ 2012-01-22 08:42:45
ReplyReply to
Great Tutorial. The code explanations are much intuitive than I have seen in many texts...

I have a basic question regarding classes. In the Introduction to C# classes, the Car class is created. This class has one (private) variable, a constructor, a method, and a property which provides a way to access the variable from the outside.

I am a little confused by the explanation of how the class is actually used in the main application. A variable of type Car is "declared". Then a new "instance is created", color is red. Then, an instance is created again, color is green.

When is the object created? Why declare it, if it is not really created till the instance is created. In the code, both instances are of the same name... "car". Are there two objects (one red, one green). If so...how do you differentiate....or when a car instance green in color was created, did this essentially just overwrite the initial car.

This whole declare vs. create an instance has me baffled.


Forum postBrant Williams @ 2012-01-23 05:12:29
ReplyReply to
OK...I figured it out. I came up with a new code snippet that, I think, better illustrates all the functionality of Classes, Properties, and Methods. I did not change anything in the Class definition from the example, but I changed the Main App use of the class a lot.

Car car1;
Car car2;

Console.Write("Select the color of car1: ");
car1 = new Car(Console.ReadLine());

Console.Write("Select the color of car2: ");
car2 = new Car(Console.ReadLine());

Console.WriteLine();

Console.WriteLine("car1 is "+car1.Describe());
Console.WriteLine("car2 is " + car2.Describe());
Console.WriteLine();

Console.Write("Change the color of car1 to: ");
car1.Color = Console.ReadLine();
Console.Write("Change the color of car2 to: ");
car2.Color=Console.ReadLine();
Console.WriteLine();

Console.WriteLine("car1 is " + car1.Color);
Console.WriteLine("car2 is " + car2.Color);

Console.ReadLine();











© net-tutorials.com 2006 - 2012

MailContact net-tutorials.com