mablevj mablevj - 9 days ago 7
Java Question

Is Java define polymorphic methods by default in opposite of what C# does?

I know that both

C#
and
JAVA
are inspired by object oriented concept

Please check the code snippet below

C# implementation

class BaseClass {
public void run() { Console.WriteLine("Base"); }
}
class DerivedClass : BaseClass {
public void run() { Console.WriteLine("Derived"); }
}

public class Program {
public static void Main(string[] args) {

BaseClass b = new DerivedClass();
b.run(); // Output: Base
}
}


JAVA implementation

class BaseClass {
void run(){System.out.println("Base");}
}
class DerivedClass extends BaseClass {
void run(){System.out.println("Derived");}

public static void main(String args[]) {

BaseClass b = new DerivedClass(); //upcasting
b.run(); // Output: Derived
}
}


The above code snippet will generate different output. Subclass method is invoked in
java
but base class method is invoked in
C#
due to 'DerivedClass.run()' hides inherited member 'BaseClass.run()'.

Also one warning in
C#
says that "
DerivedClass.run()
hides inherited member
BaseClass.run()
. Use the
new
keyword if hiding was intended. [netcoreapp1.0]".

I want to know that whether this is a remarkable difference or just by the Compiler/framework design?

Answer

In C# all methods and properties aren't polymorphic by default. Otherwise, you need to mark them with virtual keyword and an inherited class will override the whole method using override keyword:

public class A
{
    public virtual void DoStuff() {}
}

public class B : A
{
    public override void DoStuff() {}
}

Conclusion: there's no remarkable difference between Java and C# in terms of polymorphism excepting the fact that Java define polymorphic methods by default in opposite of what C# does.

Member hiding

In C#, when you define a member with the same signature as other defined in one of its parents, you're re-using an identifier and creating a new member:

public class A 
{
     public string Text { get; set; }
}

public class B : A
{
    // This hides A.Text
    public string Text { get; set; }
}

BTW, C# provides new keyword to mark that you're intentionally doing that:

public class B : A
{
    // This hides A.Text
    new public string Text { get; set; }
}

Obviously, when you upcast an instance of B to A, you're not goint to get B.Text value but A's one, because this isn't polymorphism.