Java inheritance vs. C# inheritance

前端 未结 4 958
南旧
南旧 2021-01-01 22:08

Let\'s say Java has these hierarchical classes:

class A 
{
}
class B extends A
{
    public void m()
    {
        System.out.println(\"B\\n\");
    }
}
clas         


        
4条回答
  •  青春惊慌失措
    2021-01-01 22:32

    It's for the virtual function definition:

    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).

    In C#,you should declare the method as virtual in order to be overriden, as shown in MSDN:

    • C# Lang Spec. Virtual keyword
    • C# Virtual

    Since the M method is not virtual, it will execute b.M() even if b variable is actually a D instance.

    In Java, every non-static method is virtual by default, so you when you override a method (even without the @Override annotation) the behavior of the b.M() will be the d.M() that inherits the c.M() method behavior.

    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?

    You simply can't do this in Java. The M method in C class would override the M method in B. Adding the final modifier to B#M will just make that C or other B children can't override the M() method.

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

    Change the M method in B class to virtual and override it in C class:

    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");
        }
    }
    

提交回复
热议问题