Java vs. C#

Initialization of Parent Constructor


Java
 
//super constructor called before the subclass's

public class ParentClass
{
    public ParentClass()
    {
        System.out.println("Parent Constructor.");
    }

    public void print()
    {
        System.out.println("I'm a Parent Class.");
    }
}

public class ChildClass extends ParentClass
{
    public ChildClass()
    {
        System.out.println("Child Constructor.");
    }

    public static void main(String[] args)
    {
        ChildClass child = new ChildClass();
        child.print();
    }
}

Output:
    Parent Constructor.
    Child Constructor.
    I'm a Parent Class.

public class Parent { String parentString; public Parent() { System.out.println("Parent Constructor."); } public Parent(String myString) { parentString = myString; System.out.println(parentString); } public void print() { System.out.println("I'm a Parent Class."); } } public class Child extends Parent { public Child() { super("From Derived"); System.out.println("Child Constructor."); } public void print() { super.print(); System.out.println("I'm a Child Class."); } public static void main(String[] args) { Child child = new Child(); child.print(); ((Parent)child).print(); } } Output: From Derived Child Constructor. I'm a Parent Class. I'm a Child Class. I'm a Parent Class. I'm a Child Class.

C#
 
//parent constructor called before the subclass.
using System;
public class ParentClass
{
    public ParentClass()
    {
        Console.WriteLine("Parent Constructor.");
    }

    public void print()
    {
        Console.WriteLine("I'm a Parent Class.");
    }
}

public class ChildClass : ParentClass
{
    public ChildClass()
    {
        Console.WriteLine("Child Constructor.");
    }

    public static void Main()
    {
        ChildClass child = new ChildClass();

        child.print();
    }
}
Output:
    Parent Constructor.
    Child Constructor.
    I'm a Parent Class.

using System; public class Parent { string parentString; public Parent() { Console.WriteLine("Parent Constructor."); } public Parent(string myString) { parentString = myString; Console.WriteLine(parentString); } public void print() { Console.WriteLine("I'm a Parent Class."); } } public class Child : Parent { public Child() : base("From Derived") { Console.WriteLine("Child Constructor."); } public new void print() { base.print(); Console.WriteLine("I'm a Child Class."); } public static void Main() { Child child = new Child(); child.print(); ((Parent)child).print(); } } Output: From Derived Child Constructor. I'm a Parent Class. I'm a Child Class. I'm a Parent Class.