Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Overriding-C# vs java

Tags:

java

c#

oop

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

Its just to clarify my concept.I have an code that override 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 same code I executed in java ,I got out put as "2". Just curious to know the reason as overriding principle can be differnt on languages.Sorry I have no experience in java.

Thanks

like image 745
Vicky Avatar asked Jul 19 '16 08:07

Vicky


1 Answers

In C#, if you want to make a method overridable, you have to use the keyword virtual in the superclass. Looking at your example, if you would have added virtual to the method Food in class A, the output would have been 2 instead of 1:

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

In Java, there is no virtual keyword. Methods are automatically virtual. There is no way to make a method non-virtual in Java to get the same behaviour as C#.

like image 70
Jesper Avatar answered Sep 28 '22 19:09

Jesper