Given this Java code, this outputs 0 and 4 :
class A{ A() { print(); } void print() { System.out.println("A"); } } class B extends A{ int i = Math.round(3.5f); public static void main(String[] args){ A a = new B(); a.print(); } void print() { System.out.println(i); } }
And with this identical C # code, it outputs 4 and 4
using System;
class A{ internal A() { print(); } virtual internal void print() { Console.WriteLine("A"); } } class B : A{ int i = (int) Math.Round(3.5f); public static void Main(string[] args){ A a = new B(); a.print(); } override internal void print() { Console.WriteLine(i); } }
Although I understand that the output should be 4 and 4 in Java, but in fact the answer is 0 and 4 in Java. Then I tried it in C #, answer 4 and 4
What gives? The rationale for Java is that when building, BA is still initialized (hence, I suppose B is still initialized if Java says that A is still initialized), so the default value should be 0. Therefore, the output is 0 and 4 in Java.
Why is the behavior of the C # constructor different from Java, or vice versa?
source share