The difference between Java and C #

Source: Internet
Author: User
Tags instance method static class

Constructors in Java cannot be decorated with static, whereas in C #,static constructors are used to initialize any static data, or to perform specific operations that need to be performed only once. Static constructors are used to initialize any static data, or to perform specific operations that need to be performed only once.

Java foreign class cannot be modified with static, C # can,static classes in C # contain only static members. You cannot use the new keyword to create an instance of a static class. Static classes are loaded automatically by the. NET Framework Common Language Runtime (CLR) when the program or namespace containing the class is loaded.

Use static classes to include methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not manipulate instance data and are not associated with specific objects in your code. You should use static classes to include those methods.

The main functions of static classes are as follows:

    • They contain only static members.

    • They cannot be instantiated.

    • They are sealed.

    • They cannot contain instance constructors

      //static classes, static classes in static classes public static class         singleton{public static class Nested {public static void yy () {Console.WriteLine ("yyy");    }} public static void Yy () {Console.WriteLine ("yy"); Static class public Classes singleton2{public Singleton2 () {} public}}//in ordinary class Nested {public St        atic void yy () {Console.WriteLine ("2yyy");    }} public void xx () {Console.WriteLine ("2xx");    } public static void Yy () {Console.WriteLine ("2yy");            }} class Program {static void Main (string[] args) {singleton.yy ();            Singleton.Nested.yy ();            Singleton2.Nested.yy ();            New Singleton2 (). XX ();        Console.readkey (); }} 

       

Inner class:

Instances of non-static inner classes in Java singleton.nested n = new singleton.new Nested (); C # is singleton.nested n = new singleton.nested ();

There cannot be static members in a non-static inner class in Java, which can be in C #.

The inner class in C # is called a nested class, completely different from the inner class of Java, similar to the static inner class of java. In C #, classes are distinguished by Nested class and Not-nested class, which are classes that are declared inside other data types. The latter is a class that is directly defined in a given namespace. Non-inline classes allow only public and internal access control, while built-in classes allow all access controls to be used, private,protected,protected, public and internal. Internal classes can also access all methods of an external class, including the instance method and the private method, but you need to explicitly pass an instance of an external class. One purpose of creating an inner class is to abstract the behavior of an external class in a state, or a C # inner class exists only in a particular context of an external class. Or hide implementations, by setting the inner class to private, you can set the class to be accessible only to external classes. Another important use of an inner class is when the outer class needs to work as a particular class, while the outer class has been inherited from another class, because C # does not support multiple inheritance, so create a corresponding inner class as a FA for the outer class? Ade to use.

String in Java is not a keyword

Web sticker:

November 1, 2007
1. Access control aspects: C # has public, internal, protected, private, more than Java a internal, in fact, it is similar to the Java package Access, internal represents the same compilation set (such as EXE, DLL) can be exchanged for visits.
There are differences between Protected,java and C #. In Java, protected is the same as the package access level, which is not private. In C #, protected and private are about the same, that is, the members of its flag are private.
There is a situation where a member of a class needs to be able to access it in a class, and can be accessed by other classes in the same collection (whether it's a Java package or a compiled collection in C #). In Java, just use protected. In C #, you can specify internal protected at the same time (the order of the two is arbitrary).
In a situation where a member of a class needs to be accessible to a class, but not to other classes in the same collection (whether it's a Java package or a compiled collection in C #), What to do? In C #, you can specify protected (the order of the two is arbitrary). But Java has nothing to do with it.

Comment: I like C # internal, in Java if a class to provide services for some classes in the API, in order to not expose, can only use the package-level private, and the class being served in a package, if there are more than one package of classes are to be serviced, it is impossible to do. C # 's internal is good only for classes in the current "set" (which may have multiple namespace).

However, I do not like the "collection" of C # 's gratitude. Reflection must also give the DLL or EXE file name (if not in the current DLL or EXE), and Java is not required, only under Web-inf/classess and Lib can be. Especially when the API is going to reflect its callers, how does the DLL as a class library know which EXE is calling itself?

2. C # has the concept of static constructor, which is the same as in Java, the initial module.
C #: Static [class name]{}
java:static{}

Comments: This is the original writing, I looked for a long time also did not search the static code snippet in C # How to write, now get all no effort.


3. The main function in Java must be public static void main (string[] args) or the virtual machine will refuse to run. In C #, the main function can be private (or even protected), and you can return an int value without arguments. A bit like C language.
4. Found that csc.exe has a function well, after 100 plus a lowercase l, it warns that the "l" suffix is easily confused with the number "1"; for clarity, use "L".

Comments: Ms's humane care ah.


5.c# provides a mechanism that allows a variable to be dynamically assigned once and cannot be changed later. That's the function of the ReadOnly keyword.

Annotations: This mechanism may be useful in certain situations. For example: Draw lots, so you can not cheat.

6.java is much stronger than C # in terms of inheritance and polymorphism. Java default polymorphism, C # requires virtual (inherited method) and override (inherited method), and C # requirements cannot change the original access modifier, unlike Java, you can specify a more relaxed access mode. If someone uses C # to write a program, you must always bring virtual and override, and must copy the original access control, not very depressed? Does anyone use C # 's object-oriented features to discard polymorphic features? It's going to be a lot of confusion.
Polymorphism is the essence of object-oriented, like Java is not better by default?

Annotations: C # is 90% similar to Java, but it is bound to evolve from C + +, in the concept of virtual function or continuation of C + + way. After being used to Java, it really feels awkward. Java is good: By default, it is a virtual function that allows the quilt class to be overridden, but for methods that intentionally do not want subclasses to be overridden with the final keyword.

7. New in C # can also be used to specify a method of a subclass to hide a method with the same signature for the parent class. Is this not superfluous? You don't have to, but Csc.exe will warn you, like "LAN." Other.main (string[]) "Hides inherited members" LAN. Helloworld.main (string[]) ". If it is intentionally hidden, use the keyword new.
Like Java, the default is much better.
But then again, C # has a reason for doing so. If Class B inherits from Class A, the next step is to add a method called Hi (), which is unique to B. Then class A (assuming someone else to maintain, you can not see the source code) suddenly also added a method hi (). If B's own that Hi () is different from the return value of a that hi (), when you update class library A, it may cause the program to run incorrectly or not compile. C # is a good place to avoid this problem. (Although the probability of this problem is quite small ...) )

Comments: In fact, this is still related to 6, in short, for Javaer is two words "awkward." Those non-virtual functions simply don't allow rewriting, like the final in Java. Why do you "have to be a prostitute and make a memorial?" Yes, when the warning exceeds a certain number, the estimate is buried, it is not easy to be noticed. And really wait for the use of time, which is polymorphic? Which one is "reinvent the stove"? The user is not dizzy dish is strange!

8.c#, to prevent a class from being inherited, use the keyword sealed. When defining a constant, use Const.
It would be nice to have a unified final like Java.

Comments: This is nothing, the key words are the same, it seems that others Ms more than level. We just need to remember some more things is, how helpless ah.


9. In C #, to compare two reference variables to the same object, you cannot use = = in Java, and use the ReferenceEquals method in object. In C #, you cannot use an instance of a class to invoke a class method of that class, and you must use the class name. So o1= =o2 in Java is equivalent to Object.referenceequals (O1,O2) in C #.

Annotations: All operators are overloaded with trouble. Equals is Equals;referenceequals is referenceequals. But you have to pay attention, sometimes Equals sometimes is referenceequals. = = was overloaded, I was more afraid to use, or a little bit of things to write Equals and referenceequals it, that will not make mistakes, meaningful and clear.

There is no wrapper class of the original type in 10.c#, but it also provides the function of automatic unpacking, as is the case with Java. The difference is that C # Boxing is automatic and the unboxing is forced to convert.
int i=100;
Object obj=i;
i= (int) obj;
How to install and dismantle, we do not know. Only know that the CLR has converted int to object.

Annotations: wrapper class or something? such as: string int32;string, int, and even object. Is my understanding wrong? At least the colors highlighted from the VS keyword can be separated.


The inner classes of 11.java sometimes help a lot. In C #, the only static internal classes are available. This means that the outer class is only equivalent to a namespace. Inner classes in C # can access private members of external classes, which might make it a bit of a use.

Annotations: I don't have much research on this, and I try not to use nested classes in Java. In fact, static member Class + inner class (including: Non-static member class, anonymous class, local Class) = Nested class. If you want to use the static member class preferably, the inner class is best to touch less, especially anonymous classes (but some places must use it, contradictions).


Although there are operator overloads in 12.c#, it should not be encouraged for the entire. NET consistency. Because some. NET languages do not have operator overloading, one goal of. NET is to eliminate the differences in language.

Annotations: People who are accustomed to Java must not want this "God-given". Only A = = was overloaded by Ms himself into a 9 look (in fact, people are overloaded is still very good, but we are in use when the mind is not brilliant). Do you want to overload the value class like BigDecimal +-*/? It's benevolent see, isn't it?


13.c# a struct value type, which is the same as the original type. Microsoft will help you encapsulate the struct as an object when necessary, just as you would encapsulate an int type. That you can assume that a struct is also inherited by object, although the struct itself does not support inheritance. (a struct can be initialized without new, but its contents must be initialized to invoke its method; struct has no destructor; struct does not have a default constructor method).

Annotations: Why structs appear in C # I really dare not to guess, from C + + lineage? Or is it slightly better than class in performance, as Ms says? In short, just know that you can use it when building a value class.



November 2, 2007
The access control for classes in 1.java can only be public, or not (that is, the default package access). But in C #, the access control for class and interface can be public/private/internal/protected/internal protected. Of course, you must first obtain access to the class before you can access the members of the class.

A class or interface in a C # collection that can contain more than one public is not related to the file name.

Comment: Ms does not have an official suggestion for naming the namespace like Sun (Sun suggests that the naming of the package is a reverse order of the domain names, all lowercase letters). And. NET also does not require that classes be saved by directory and file name (Java does not have this requirement at first). Which Way is better? I think it's a matter of habit, at least I think the Java way is clearer. and a lot. NET project, open after all the source files are in a "big flat layer", it is difficult to be said.


The interfaces in 2.c# cannot contain constants, while Java can.

Annotations: should/can include definitions of constants in an interface? The public is justified in saying that the PO is justified. Personally, even if Java runs, try not to do so.


The as in 3.c# is the same as the instanceof function in Java. But C # provides an as keyword that is said to be more efficient.

Comment: The original author's error? Should it be? As is a forced type conversion, and the more common variable a = (type) variable B; The difference is that if the conversion fails, the AS returns NULL, and the parentheses convert back to throw an exception. As is the same syntax as the AS3 language.


4. Interfaces and abstract classes are similar in C # and Java, where the distinction between interface design and abstract class design is mentioned. If you change the design of an interface, such as adding a method, users who use your previous code will have to change their code otherwise they cannot run and compile. But if it is an abstract class, you can provide a method with a default implementation, and the user's code does not need to be changed.

Annotations: This fact is the same in both Java and C #. However, the selection of interfaces and abstract classes (even if they include skeleton classes) is not the basis for this, it is just a performance. Again, once the interface is released, it is your commitment to the outside. Even the version upgrade can no longer make any changes, even adding new methods. How do you want to increase it? If the same skeleton class is also controlled in your hand, you can do this by using the skeleton class (which is actually a usage of the abstract class, the skeleton class implements the interface, the actual class inherits the skeleton class, the skeleton class can implement some common, or default methods for the actual class) to provide a new method of the default implementation to achieve the purpose. This is not advisable, however, because the new methods that need to be added to the version upgrade are often real methods of doing things, and giving a default implementation in a skeleton class is often meaningless. A better approach is to write a new interface to inherit the original interface and declare the new method in the sub-interface. This keeps the 100% forward compatible, and the class that needs to implement the new method belongs to the class that accompanies this interface upgrade or will be implemented later.


When a class implements an interface in 5.c#, its related methods do not have to indicate override, but when a class inherits an abstract method of an abstract class, it must be added with override, otherwise it is considered hidden. (In fact, only abstract methods, or virtual, or interface methods can be overridden, override.) Do not override without reason. )

Comment: This also has nothing to say, each family has the writing of each family, if has to be said also is the habit question. 6 of the previous half.


6. There is a "polymorphic starting point" problem in C #. If a class implements a method of an interface, only the interface to the class has a polymorphic function, to this polymorphic inheritance, the class must indicate that it is virtual, polymorphic start, the next subclass provides override can be polymorphic, do not need more virtual.

The abstract method of abstract classes, however, defaults to a polymorphic starting point, and subsequent subclasses simply override the line.

Comments: Feeling or the same half of the 6. Maybe I haven't really understood it yet?


7. When a class implements two interfaces and two interfaces have an identical method definition, C # has a resolution mechanism called the display implementation. Java simply does not deal with this situation, anyway, after implementation can be called, do not have to indicate which interface, left to the programmer to consider.
Of course, there are other features in the display implementation in C #. As an example, interface A has a method called F () and Class B implements a. An instance of B is supposed to be free to call F (), but if there is a requirement that an instance of B be cast to a before it can call F (). In Java, such unreasonable requirements are not allowed. But C # can do that by showing the way it is implemented. Who would use such a feature?

Annotations: Two interfaces If you define the same method, the method name, the number of arguments, the type of the parameter, the type of return value, the exception that can be thrown (this C # really does not), then when you implement it, what is the interface from? Is that necessary? Java is "stupid" here, I look good.

The difference between Java and C #

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.