views:

130

answers:

2
public class Animal  
{  
    public Animal()  
    {  
        Console.Writeline("Animal");  
    }  
}  

public class Snake : Animal  
{  
    public Snake()  
    {  
        Console.Writeline("Snake");  
    }  
}  

How many objects will be created in each of the following codes below?
(Refer to the above code...)

  1. Animal myAnimal = new Animal();

  2. Snake mySnake = new Snake();

  3. Animal myAnimal = new Snake();

+2  A: 

Since your code is C#, open Visual Studio. Create a new Console project. Paste your code into Class1.cs. Add your three lines into the "Main" method. Comment out 2) and 3) and run your .exe. Now comment out 1) and 3) and re-run your .exe. Finally comment out 1) and 2) and re-run your .exe. Now you have answered the question yourself.

Kirk Woll
sorry sir, will you please explain how can I know the answer by running it in visual studio? Is there a specific window during debugging that I can visually see all objects created? I'm just asking because I really dont know... sorry...
Hisoka
You're writing to the console. Go to a command prompt and execute the .exe you will have generated by compiling your code. You will see a line for each instantiation. Otherwise, run it under the debugger and simply put a breakpoint on each Console.WriteLine, which will accomplish the same thing as you take not of each time it hits the break point.
Kirk Woll
+7  A: 

In total (not counting the Program object you're running this code with, or any additional objects beyond the scope listed here), there will be 5 objects created:

  • 2 Snake objects
  • 1 Animal object
  • 2 String objects

The string literals you are using will be interned in the intern pool (see http://csharpindepth.com/Articles/General/Strings.aspx), and therefore they will not be created more than once.

John Rasch
this is the correct answer
Stan R.
Thanks for taking the time to explain it all.
EKS
thank you very much...
Hisoka