Reputation: 331
I am trying to make an equivalent code in C# for a piece of code that I already have in Java. The Java code is as follows.
class Test
{
public static void main (String args[])
{
C1 o1 = new C1();
C2 o2 = new C2();
System.out.println(o1.m1() + " " + o1.m2() + " " + o2.m1() + " " + o2.m2());
}
}
class C1
{
void C1() {}
int m1() { return 1; }
int m2() { return m1(); }
}
class C2 extends C1
{
void C2() {}
int m1() { return 2; }
}
This gives the output 1 1 2 2. Now, I have written this code for C#.
class Program
{
static void Main(string[] args)
{
C1 o1 = new C1();
C2 o2 = new C2();
Console.WriteLine(o1.M1()+ " "+ o1.M2()+ " "+ o2.M1()+ " "+ ((C2)o2).M2()+ "\n");
Console.ReadKey();
}
}
public class C1
{
public C1()
{
}
public int M1()
{
return 1;
}
public int M2()
{
return M1();
}
}
public class C2:C1
{
public C2()
{
}
public int M1()
{
return 2;
}
}
This, however, prints 1 1 2 1 as the inherited M2 in C2 calls the M1 in C1 and not the M1 in C2. How can I make it call M1 in C2 with minor modifications?
Upvotes: 0
Views: 513
Reputation:
Note: in C# you need to use virtual
and override
keywords to allow overriding.
MSDN :
The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.
(my bolding)
class Program
{
static void Main(string[] args)
{
C1 o1 = new C1();
C2 o2 = new C2();
Console.WriteLine(o1.M1() + " " + o1.M2() + " " + o2.M1() + " " + ((C2)o2).M2() + "\n");
Console.ReadKey();
}
}
public class C1
{
public C1()
{
}
public virtual int M1()
{
return 1;
}
public int M2()
{
return M1();
}
}
public class C2 : C1
{
public C2()
{
}
public override int M1()
{
return 2;
}
}
Upvotes: 2