Overriding method - C # vs java

Is principle overriding method different in Java from C #? I am working for C # and now asked to debug code in java.

Its just to clarify my concept. I have code that overrides a method in C #.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication1
{
   public  class A
    {
        public void Food()
        {
            Console.Write("1");

        }


    }

    public class B : A
    {
        public  void Food()
        {
            Console.Write("2");
        }

    }

    public class program
    {

        static void Main(string[] args)
        {
            A a = new B();
            a.Food();               

            Console.ReadLine();

        }
    }

}

OUTPUT -1 (no doubt) (in C #), but when the same code that I executed in java, I chose as "2". It’s just curious to know the reason, since the principle of redefinition can be different in languages. Sorry, I have no experience in java.

thank

+4
source share
2 answers

#, overridable, virtual . , virtual Food A, 2 1:

public class A
{
    public virtual void Food()
    {
        Console.Write("1");
    }
}

Java virtual. virtual. Java, , #.

+7

,

A a = new B() a.Food();

Foo A.

, , ,

B a = new B() a.Food();

, , , Foo B.

, , , , .

, , virtual, #. override .

public  class A
{
    public virtual void Food()
    {
        Console.Write("1");

    }


}

public class B : A
{
    public override void Food()
    {
        Console.Write("2");
    }

}

, , , ? ( )

public class C : B
{
    public override void Food()
    {
        Console.Write("2");
    }

}

B , .

0

Source: https://habr.com/ru/post/1648341/


All Articles