Want to show your appreciation? Please to my charity.

Friday, May 11, 2012

C# to Java–Type System

This is one of the informal discussions with a group undergoing the transition from C# to Java.

Type System

 

C#

The common type system in the .NET Framework supports the following five categories of types: class, delegate, structure(struct), enumeration(enum) and interface.

Except interface type by itself cannot create concrete object, types are further categorized by data type into value type and reference type. A value type holds the data within its own memory allocation. A reference type contains a pointer to another memory location that holds the data. Class and delegate are reference types and struct and enum are value types.

All .Net types except interfaces inherit from ultimate base class System.Object.

All primitive types are structures, which also inherits from System.Object.

.Net Array is a class type.

Java

There are two kinds of types in the Java programming language: primitive types and reference types.

There is also a special null type, the type of the expression null, which has no name. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

Java primitive type does not inherit from java.lang.Object and Java has no user defined value type. This is a disadvantage over .Net.

Java language specification categorized reference type by how they appear in language structure. But essentially, reference type can be further categorized into class type and interface type.

Java enum is a special class type. This is a big advantage over .Net.

Java has no delegate. Needless to say lamba expression. This is a huge disadvantage. The workaround is to use interface and anonymous class. Example:

public Comp() {
    List<String> foo = new LinkedList<String>();
    Collections.sort( foo, new Comparator<String>() {
        public int compare( String s1, String s2 ) {
            return s1.compareTo( s2 );
        }
    });
}

with many limitations.

Inheritance

Although .Net allows multiple inheritance of classes, C# language allows class to inherit form only one base class and can implement multiple interfaces. Interface can in turn inherit multiple interfaces. Java is same as C# on this.

Misc

C# use sealed keyword to prevent other class from inheriting it. Java uses final keyword.

C# use static keyword to make a class not insatiable. Java has no counterpart for this. The workaround is to use private constructor. Java has complete different use of static modifier of class and we’ll cover in a later session about member class.

The meaning of abstract class is identical in C# and Java

No comments:

Post a Comment