J
James Carnley
I am moving over from Java and have found something strange in the way
C# works. Can anyone explain this to me?
I have 4 classes which I all want to share one Print method yet each
class will have its own variables to be used in Print.
The Print statement just prints out the variable "num1". Class1 has
"num1" set to 1 so it prints 1. Class 2 has "num1" set to 2 yet it still
prints 1... why? Class 3 and 4 do this also. In java it prints out the
value of num1 in whatever class the mathod was called in.
The code is as follows:
using System;
namespace BlankTestProject
{
public class TestMain
{
public static void Main()
{
Class1 class1 = new Class1();
Class2 class2 = new Class2();
Class3 class3 = new Class3();
Class4 class4 = new Class4();
Console.WriteLine("These should all be different");
class1.Print();
class2.Print();
class3.Print();
class4.Print();
Console.WriteLine("\nPress enter to exit.");
Console.ReadLine();
}
}
public class Class1
{
int num1;
public Class1()
{
}
public void Print()
{
Console.WriteLine(num1);
}
}
public class Class2 : Class1
{
int num1 = 2;
public Class2()
{
}
}
public class Class3 : Class2
{
int num1 = 3;
public Class3()
{
}
}
public class Class4 : Class3
{
int num1 = 4;
public Class4()
{
}
}
}
C# works. Can anyone explain this to me?
I have 4 classes which I all want to share one Print method yet each
class will have its own variables to be used in Print.
The Print statement just prints out the variable "num1". Class1 has
"num1" set to 1 so it prints 1. Class 2 has "num1" set to 2 yet it still
prints 1... why? Class 3 and 4 do this also. In java it prints out the
value of num1 in whatever class the mathod was called in.
The code is as follows:
using System;
namespace BlankTestProject
{
public class TestMain
{
public static void Main()
{
Class1 class1 = new Class1();
Class2 class2 = new Class2();
Class3 class3 = new Class3();
Class4 class4 = new Class4();
Console.WriteLine("These should all be different");
class1.Print();
class2.Print();
class3.Print();
class4.Print();
Console.WriteLine("\nPress enter to exit.");
Console.ReadLine();
}
}
public class Class1
{
int num1;
public Class1()
{
}
public void Print()
{
Console.WriteLine(num1);
}
}
public class Class2 : Class1
{
int num1 = 2;
public Class2()
{
}
}
public class Class3 : Class2
{
int num1 = 3;
public Class3()
{
}
}
public class Class4 : Class3
{
int num1 = 4;
public Class4()
{
}
}
}