Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base class c# and Java different behaviour

Tags:

java

c#

using System;
using System.Collections.Generic;
using System.Text;

public class Based
{
   public string fun()
    {
        return " I am based";
    }
}

public class Derived :Based
{
    public string fun()
    {
        return " I am derived";
    }

}

namespace ConsoleApplication8
{
    class Program
    {

        static void Main(string[] args)
        {
            Based br = new Derived();;

            Console.Write(br.fun());
        }


    }
}

Hi All , I have written small piece of code in Java and as well as in c# also.

But I am getting different outputs. Could you please explain.

In java I am getting " I am derived" , while in c# am getting " I am based" . Could you please explain to me why? and also when do we use following syntax

Baseclass obj = new Derivedclass().
like image 831
user2329702 Avatar asked Dec 11 '22 23:12

user2329702


1 Answers

In Java all methods are virtual by default, but in C# they are not. Therefore in C# you have to mark virtual methods manually.

Modify your code:

public class Based
{
    public virtual string fun()
    {
        return "I am base";
    }
}

public class Derived : Based
{
    public override string fun()
    {
        return "I am derived";
    }
}
like image 157
General-Doomer Avatar answered Dec 26 '22 23:12

General-Doomer