Java Vs C#继承实现多态
java vs c#, 继承实现多态
java 和 c# 对于继承时,多态的实现有很大的差异。
下边的例子, 同样的代码:
c# print: animal
;java print: dog
想要 c# 输出 dog,需要修改代码为 demo3.
父类方法添加 virtual
, 子类方法添加 override
参考: https://stackoverflow.com/questions/13323099/java-inheritance-vs-c-sharp-inheritance
-
In java all of methods are virtual by default. And methods in derived classes override methods from base
. In C# they are not. -
Declare this method with virtual keyword in base class and with override in derived.
java 默认方法都是 virtual,子类里相同签名的方法都是 override。 在 java 里用继承来实现多态的限制少
c# 里对用继承来实现多态的限制多,需要同时修改 父类和子类
// demo1, c#
public class Test
{
public static void Main(string[] args)
{
Animal animal = new Dog();
animal.Print();
//out: animal
}
}
class Animal
{
public void Print()
{
Console.WriteLine("animal");
}
}
class Dog : Animal
{
public void Print()
{
Console.WriteLine("dog");
}
}
// demo2, java
public class InheritanceDemo {
public static void main(String[] args) {
Animal animal = new Dog();
animal.print();
// out: dog
}
}
class Animal {
public void print() {
System.out.println("animal");
}
}
class Dog extends Animal {
public void print() {
System.out.println("dog");
}
}
// demo3, c#
public class Test2
{
public static void Main(string[] args)
{
Animal2 animal2 = new Dog2();
animal2.Print();
// out: dog
}
}
class Animal2
{
// add virtual
public virtual void Print()
{
Console.WriteLine("animal");
}
}
class Dog2 : Animal2
{
// add override
public override void Print()
{
Console.WriteLine("dog");
}
}