C #, Java comparison

Source: Internet
Author: User
Tags access properties define array bool functions header net access
A lot of people say that C # is the weapon that Microsoft uses to compete with Java, because the two have a great deal of similarity, but there are a lot of different places, the so-called "see the difference in nuances". So where are the similarities and differences between the two? From today onwards, we will compare the features of C # and Java from various angles, hoping to help friends who are learning and using C #.

1. Overview of C # and. NET Platforms

June 2000, Microsoft releases the 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

The following is a simple list of C # and Java similarities, although here we focus on the differences between C # and Java, but it is also necessary to understand the similarities.

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

Automatically reclaims garbage memory and eliminates pointers (pointers can be used in C #, but must be marked with unsafe keywords)

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);

In C #, however, such a method is "attributed". The same code, in C #, becomes:

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

As you can see, C # is clearly 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, attribute members are referred to in C # 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, get and set in C # must appear in pairs, a property cannot have only get without set (in Java and C + + you can have only got or set), the advantage of doing so in C # is that it is easy to maintain, and if you want to modify a property, you will pay attention to both the get and set methods , at the same time modify, will not change this forget that.

4. Object indexing mechanism (Indexer)

The object indexing mechanism is introduced in C #. To be clear, object indexing is actually an 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 object array of this program.
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?) 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 even 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

What are the characteristics of the reference? An obvious feature is that it has a pointer behavior, as if from Java back to C + +. In C #, the function of the reference is probably the same as the pointers in C + + and the interfaces in Java. 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 # is directly supported for events (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 create a game object and a referee object, and then we 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 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 anaphora mechanism was in MSVJ, which was invented by Anders Hejlsberg and is now used in C #. 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.