C#,java comparison

Source: Internet
Author: User
C #, Java comparison
A lot of people say C #is a weapon that Microsoft uses to compete with Java, because the two are surprisingly similar to a large extent, but there are also many different places, the so-called "see the difference in detail." So where are the similarities and differences between the two? We'll start from today and we'll look at it from every angle. C #And Java features, I hope to be able to learn, use C #Friend is helpful.

1, C #Overview of the. NET Platform

June 2000, Microsoft releases C #Language and. NET platform. C #Language is a strong type, object-oriented language, it has a simple syntax, strong expression of the characteristics, and the. NET platform is composed of Microsoft. NET Plan "is the cornerstone.

. NET platform's core includes two aspects, on the one hand is the famous common language running machine (Common Language Runtime), although this noun has been obscure, but you can compare it with the Java Virtual machine, both accomplish the task is roughly the same On the other hand is a bunch of general-purpose library functions that can be invoked in multiple languages, and compile all produce a common intermediate language (intermediate Language), which can also be likened to Java bytecode, although in some different ways.

2, C #and Java

below, simply put C #and Java similar to the list, although here we focus on the C #and Java differences, but it is also necessary to understand the similarities between the two.

Both are compiled into Cross-platform, Cross-language code, and the code can only run in a controlled environment

Garbage memory is automatically reclaimed and the pointer is removed ( C #You can use pointers, but you must note the unsafe keyword)

Do not require a header file, all code is limited to a scope by "package (Package)", and because there is no header file, it eliminates the cyclic dependency of the class definition

All classes are derived from objects, and memory must be allocated using the New keyword

Use object locking to support multithreading

Has the concept of an Interface (interface)

Inner class

Inheriting a class is not inherited with a specific access right;

No global function or constant, all must belong to class;

The array or string has its own length calculation and boundary checking;

Use only "." Operators, no "->" and "::";

"Null", "Boolean" and "bool" became keywords;

Any variables are initialized before use;

You cannot use integers to return to an if conditional statement, you must use a Boolean value;

"Try" module can have "finally";

3. Properties (property)

The concept of attributes should be familiar to everyone, and class member functions are free to access any attribute members in this class. But it's cumbersome to access properties from one class to another, so many times we use the GetXXX and Setxxx methods to look unnatural, such as in Java or C + +, where the code is:

Foo.setsize (GetSize () + 1);
Label.getfont (). Setbold (True);

However, in C #, such a method is "attributed". The same code, in the C #It becomes:

foo.size++;
Label.font.bold = true;

As you can see, C #Obviously easier to read and understand. We can see something like this in the subroutine code for this "property method":

Java/c++:

public int GetSize ()
{
return size;
}

public void setSize (int value)
{
size = value;
}

C #:
public int Size
{
Get{return size;}
Set{size = value;}
}

To differentiate between this attributed method and the property members of the class, the C #Attribute members are referred to as field, and property becomes the term for this "attributed method". Incidentally, in fact, such a method of Attribution in VB and Delphi is often encountered in VB, it is also called properties.

In addition, in C #The get and set must appear in pairs, and a property cannot have only got and no set (in Java and C + +, you can have only got or set). C #The advantage of doing this is easy to maintain, if you want to modify a property, you will pay attention to both get and set method, while modifying, will not change this forget that.

4. Object indexing mechanism (Indexer)

   C #Object indexing mechanism is introduced in this paper. To be clear, object indexing is actually Array of Objects。 This is associated with the attributes in the previous section. For the purposes of this, properties need to hide the get and set methods, whereas in the indexing mechanism, the get or set methods of each object are exposed. For example, the following example illustrates this more clearly.

public class skyscraper
{
Story[] Stories;
public Story this [int index] {
get {
return stories [index];
}
set {
if (value!= null) {
stories [index] = value;
}
}
}
...
}

Skyscraper empirestate = new skyscraper (...);
empirestate [102] = new Story ("The Top One", ...);

Oh, with this feature, we can no longer be afraid of the classroom teacher told us to write Array of ObjectsThis procedure.
5. Reference (Delegate)
Refers to this thing is very special, it is a bit like a pointer, but not completely, but you can still see it as a type of safe, object-oriented pointers. (What is type safety and object oriented you don't have to talk about it.) By the way, there are a lot of books on the translation of delegate into agents, I think this is not accurate, translated into "refer to" more appropriate, the truth is consistent, and also in line with its original meaning-Microsoft is to use delegate to "replace the pointer", so called "reference", hehe.

Speaking of the reference, perhaps so far sun will be angrily to it, why. Because there is no such thing in Sun's standard Java, it is the "new feature" added by Microsoft's 99 msvj++6. To this end, two companies have a great deal of noise, and also dedicated to write a large number of articles on the Internet to attack each other, interested friends can go to see (only English version).
Http://www.Javasoft.com/docs/white/delegates.html
Http://msdn.microsoft.com/visualj/technical/articles/delegates/truth.asp

The words return to the true story, the reference has what characteristic. An obvious feature is that it has a pointer behavior, as if from Java back to C + +. In C #, refers to the completion of the function probably and C + + inside the pointer, as well as the interface in Java is equivalent. However, the reference is more sophisticated than the "authentic pointers" of C + +, because it can have multiple methods at the same time, the equivalent of C + + pointer can point to multiple functions, and is type-safe, which embodies its "object" characteristics, compared to the Java interface, The point is that it can invoke a function without having to go through the inner class, or invoke multiple functions with a small amount of code, which embodies its "pointer" attribute. Oh, there is a "wave-particle duality" flavor it. The most important application of the reference is the handling of the event, which we will focus on in the next section.

6, Events (event)

   C #The event is directly supported (this feature is also MSVJ). At present, many mainstream program language processing events are different, Delphi is the function of the pointer (this in the Delphi term is "closure"), Java with the adaptation class to achieve, VC with WINDOWSAPI message system, and C #The delegate and event keywords are used directly to solve the problem. Let's take a look at an example that gives you the whole process of declaring, invoking, and handling events.


The first is the declaration of a reference, which defines the event signal that wakes a function
public delegate void Scorechangeeventhandler (int newscore, ref bool cancel);

Define a class that generates events
public class Game
{
Note that the event keyword is used here
public event Scorechangeeventhandler Scorechange;
int score;
Score Property
public int Score
{
get {
return score;
}
set {
If (score!= value)
{
bool Cancel = false;
Scorechange (value, ref cancel);
if (! Cancel)
Score = value;
}
}
}


Classes that handle events
public class referee
{
Public referee (Game Game)
{
The referee is responsible for adjusting the score changes in the game
Game. Scorechange + = new Scorechangeeventhandler (game_scorechange);
}

Notice how the function here is the number of the scorechangeeventhandler signal.
private void Game_scorechange (int newscore, ref bool cancel)
{
if (NewsCore < 100)
System.Console.WriteLine ("Good Score");
Else
{
Cancel = true;
System.Console.WriteLine ("No Score can be so high!");
}
}
}

Main function class for testing the above characteristics
public class Gametest
{
public static void Main ()
{
Game Game = new Game ();
Referee Referee = new Referee (game);
Game. Score = 70;
Game. Score = 110;
}
}

In the main function, we CreateA game object and a referee, and then we'll see how the referee responds to this by changing the score of the game.

Please note that in our system, the game object does not feel the presence of the referee, the game object is only responsible for generating events here, as for who will listen to the event and respond to it, game object is not to make any statement.

We notice that in the referee function of the referee class, what does it mean to use the + = and-= operators after the Game.scorechange? Back to where we define scorechange, we can see that scorechange is decorated with the event keyword, so the meaning here is clear: Scorechange is an event, and events are triggered, and the corresponding event handling mechanism is required, +=/-= is to add/remove the corresponding event handler for this event, and not one event can only correspond to one handler, we can also add/remove several event handlers for the same event with these two operators. What do you think. It's very convenient.

In practical applications, the system that is similar to the one we are talking about (contest-referee) mechanism is the graphical user interface system. The game object can be seen as a small part of the graphical interface, and a score event is the equivalent of a user input event, and the referee is the equivalent of an application that handles user input.

The first appearance of the surrogate mechanism was in MSVJ, which was invented by Anders Hejlsberg, and now it is used C #In The consequences of substitution in the Java language have led to a great deal of controversy and discussion about the relationship between Microsoft and sun on classes and pointers. Interestingly, the inventor of Java, James Gosling, is very humorous to address the inventor of the Anders Hejlsberg as "' Mr. Function pointer ', because Anders Hejlsberg always find ways to put the pointer in various languages But someone who has seen a lot of the use of various classes in Java, also jokingly called Java inventor James Gosling as "' All Is class ' Sir", is really the taste, do not say in the.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.