gpt4 book ai didi

c# - Java 继承与 C# 继承

转载 作者:搜寻专家 更新时间:2023-10-30 19:41:20 27 4
gpt4 key购买 nike

假设 Java 有这些分层类:

class A 
{
}
class B extends A
{
public void m()
{
System.out.println("B\n");
}
}
class C extends B
{
public void m()
{
System.out.println("C\n");
}
}
class D extends C
{
public static void main(String[] args)
{
A a = new D();
// a.m(); // doesn't work
B b = new D();
b.m();
C c = new D();
c.m();
D d = new D();
d.m();
}
}

这是 C# 中相同代码的(盲)复制:

using System;
class A
{
}
class B : A
{
public void M()
{
Console.WriteLine("B");
}
}
class C : B
{
public void M() // I need to use public new void M() to avoid the warning
{
Console.WriteLine("C");
}
}
class D : C
{
public static void Main(String[] args)
{
A a = new D();
// a.M(); // doesn't work
B b = new D();
b.M();
C c = new D();
c.M();
D d = new D();
d.M();
}
}

当我执行 Java 代码时,我得到 C-C-C 而 C# 返回 B-C-C

对我来说,C# 的结果更有意义,因为引用 B 调用了它自己的方法。

  • Java 设计者决定打印 C-C-C 而不是 B-C-C 背后的逻辑是什么?我的意思是,为什么引用 B 使用 C 中的覆盖方法?这种方法有什么优势?
  • 如何更改 Java 代码以像 C# 一样打印出 B-C-C?我的意思是,我如何教 java 调用它使用的确切引用的方法?
  • 如何更改 C# 代码以打印出 C-C-C?我的意思是,我如何教 C# 调用覆盖方法?

最佳答案

它用于 virtual function定义:

a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of object-oriented programming (OOP).

在 C# 中,您应该将方法声明为虚拟的以便被覆盖,如 MSDN 所示:

M方法不是虚拟的,它将执行 b.M()即使b变量实际上是一个 D实例。

在 Java 中,默认情况下每个非静态方法都是虚拟的,因此当您覆盖方法时(即使没有 @Override 注释)b.M() 的行为将是 d.M()继承了 c.M()方法行为。

How can I change Java code to print out B-C-C just like C# does? I mean, how can I teach java to invoke the method of the exact reference it uses?

您根本无法在 Java 中执行此操作。 M C 中的方法类将覆盖 M B 中的方法.添加 final B#M 的修饰符只会使C或其他B children 不能覆盖 M()方法。

How can I change C# code to print out C-C-C? I mean, how can I teach C# to invoke the overriding method?

更改 M B 中的方法类别为 virtual并在 C 中覆盖它类:

class B : A
{
public virtual void M()
{
Console.WriteLine("B");
}
}
class C : B
{
public override void M() // I need to use public new void M() to avoid the warning
{
Console.WriteLine("C");
}
}

关于c# - Java 继承与 C# 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13323099/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com