Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Vs C#: Java and C# subclasses with method overrides output different results in same scenario

Ok! I have same code written in Java and C# but the output is different!

class A
{
    public void print() 
    {
        Console.WriteLine("Class A");
    }
}

class B : A 
{
    public void print()
    {
        Console.WriteLine("Class B");
    }
}

class Program
{
    static void Main(string[] args)
    {
        A a = new B();
        a.print();
        Console.Read();
    }
}

Output: Class A. It is in C#.

But when same code was ran in Java, the output was Class B. Here is the Java Code:

class A
{
    public void print() 
    {
        System.out.println("Class A");
    }
}

class B extends A 
{
    public void print()
    {
        System.out.println("Class B");
    }
}


public class Program{

 public static void main(String []args){
    A a = new B();
    a.print();
 }
}

So, why this is showing different results? I do know that, in Java, all methods are virtual by default that's why Java outputs Class B.

Another thing is that, both languages claim that they are emerged or inspired by C++ then why they are showing different results while both have same base language(Say).

And what does this line A a = new B(); actually doing? Isn't a holding object of class B? If it is so, then why C# displays Class A and Java shows Class B?

NOTE This question was asked in interview with the same code provided above. And I answered with output Class B (with respect to Java) but he said Class A will be right output.

Thank you!

like image 967
Faizan Mubasher Avatar asked Jan 22 '14 11:01

Faizan Mubasher


People also ask

What is difference between C & Java?

C is a middle-level language as it binds the bridges between machine-level and high-level languages. Java is a high-level language as the translation of Java code takes place into machine language, using a compiler or interpreter. C is only compiled and not interpreted. Java is both compiled and interpreted.

Which is better to learn first C or Java?

Should I Learn Java or C++ first? Most programmers agree that Java is easier to learn first. Java's syntax is usually easier for new programmers to understand.

Is C faster or Java?

Elapsed Time. Based on these results, C is 2.34 times slower than Java and Python is 33.34 times slower than Java.


2 Answers

This is because in C# methods of derived classes hide, not override, methods of their base class. The methods that you would like to override need to be explicitly marked with the keyword virtual in the base, and with the keyword override in the derived classes.

In contrast, in Java all methods are virtual by default: simply specifying the same signature is sufficient for an override.

Here is how to make your C# program an equivalent of Java program:

class A
{
    public virtual void print() // Add "virtual"
    {
        Console.WriteLine("Class A");
    }
}

class B : A 
{
    public override void print()// Add "override"
    {
        Console.WriteLine("Class B");
    }
}

After A a = new B(), variable a is holding object of B but the output is "Class A"! Shouldn't it call method of class B?

When you hide a method, rather than overriding it, your derived class keeps both methods - the one in the base class, and the one in the derived class. Both these methods remain accessible to the outside callers. They can decide which of the two methods to call by using an object of an appropriate static type. Here is an example:

    B b = new B();
    b.print();      // Prints "Class B"
    ((A)b).print(); // Prints "Class A"

Demo on ideone.

When you use virtual/override, you can access only one method from the outside - namely, the one in the derived class. The method in the base class can be accessed by methods of the derived class, but not by the outside users of the derived class.

like image 145
Sergey Kalinichenko Avatar answered Oct 13 '22 18:10

Sergey Kalinichenko


In Java, non-static methods are virtual, whereas in C#, they are not. You will need to use the virtual and override keywords on your print method to get the same behaviour in c#.

Polymorphic behaviour in C#:

class A
{
    public virtual void print() 
    {
        Console.WriteLine("Class A");
    }
}

class B : A 
{
    public override void print()
    {
        Console.WriteLine("Class B");
    }
}

Edit

Getting back to your original C# code, you will get a compile time warning on B.print when you use the same method signature in both a subclass and its superclass, viz:

The keyword 'new' is required on 'print' because it hides method 'MyNamespace.A.print()'

This is a good indication that the method won't be called polymorphically / virtually. To avoid the warning (and retain your original C# behaviour), in B you would need to add new:

    public new void print()
like image 21
StuartLC Avatar answered Oct 13 '22 19:10

StuartLC