Thursday, February 10, 2011

Inheritance in c# and java

Interfaces, Yes. Multiple Inheritance, No

C#, like Java, supports the concept of an interface which is akin to a pure abstract class. Similarly C# and Java both allow only single inheritance of classes but multiple inheritance (or implementation) of interfaces.

Unextendable Classes

Both Java and C# provide mechanisms to specify that a class should be the last one in an inheritance hierarchy and cannot be used as a base class. In Java this is done by preceding the class declaration with the final keyword while in C# this is done by preceding the class declaration with the sealed keyword. Below are examples of classes that cannot be extended in either language
C# Code
sealed class Student {
string fname;
string lname;
int uid;
void attendClass() {}
}

Java Code
final class Student {
String fname;
String lname;
int uid;
void attendClass() {}
}



Inheritance Syntax

C# uses C++ syntax for inheritance, both for class inheritance and interface implementation as opposed to the extends and implements keywords.
C# Code
using System;

class B:A, IComparable{

int CompareTo(){}

public static void Main(String[] args){

Console.WriteLine("Hello World");

}
}

Java Code
class B extends A implements Comparable{

int compareTo(){}

public static void main(String[] args){

System.out.println("Hello World");

}
}
Since C# is aimed at transitioning C++ developers the above syntax is understandable although Java developers may pine for the Java syntax especially since it is clear from looking at the class declaration in the Java version whether the class is subclassing a class or simply implementing an interface while it isn't in the C# version without intimate knowledge of all the classes involved. Although it should be noted that in .NET naming conventions, interface names have an upper-case "I" prepended to their names (as in IClonable), so this isn't an issue for programs that conform to standard naming conventions.

No comments:

Post a Comment