A contrastive analysis of C # syntax and Java syntax

Source: Internet
Author: User
Tags modifiers



The early development of the time has been used in C + +, and later mainly Java. You need to use C # recently.



Familiar with the next C #, found that the C # language on the basis of a lot of simplification, and reference to a lot of Java grammar habits, originally in the syntax of C + + has a lot of Java and similar places, now C # similar places more, but there are many differences.



This article summarizes the syntax differences between C # and Java, facilitating mutual learning and strengthening understanding.



A comparison of basic grammar



1. Program Framework



Like Java, C # requires that all code be in the class, no longer the same as C + +, to define a class, or to define a global approach.



The entry code for a Java program must be the following method in a class:



public static void Main (string[] args);



In C #, the entry method is



static void Main (string[] args)



Note: The first letter m of Main in C # is uppercase, and the parameters of the main method can be undefined. The modifiers of the method can also be non-public.






2. Packages and namespaces



In Java, Java source files are organized through packages. In C #, you organize C # source files through namespaces. They are similar in meaning and function.



The difference is that Java enforces that the Java source files must be kept in strict accordance with the package path.



In Java, a package is introduced through import, whereas in C # a namespace is introduced through a using.



Both can refer to the class through the full path (so that no import and using is required).






3. Basic data type



The names of most of the basic types are the same, such as int, char, and so on. The keywords that are defined by the enumeration are enum. Array definitions and usage syntax are similar.



The typical difference is:



1) A Boolean is a Boolean in Java, whereas in C # is bool.



2) String type name is string in Java, and string in C # (the first letter S is lowercase).



The key is to compare string content in Java with the Equlas method, whereas in C # you can compare it directly with = =.






4. Statements



If statements, switch statements, For,while, do ... while,break, continue are used in the same way.



One difference is that in Java, you can iterate through a collection with a For loop. In C #, you need to traverse with a separate keyword, foreach, but using the same method.






Comparison of object-oriented syntax



Both Java and C # define classes through the Class keyword and do not require a header file. The implementation code for the class is expanded with {}.



1. Members of the class



The concept of a property is introduced in C #.



We know in Java, in order to improve security, we define member variables to move the proposed definition of private, so that other classes can access the variable, and then define the corresponding get and set methods, code such as:


 
class A{ private int num; public void setNum(int num) { this.num = num;
    } public int getNum() { return num;
    }
} class B{ public void test(){
        A a = new A();
        a.setNum(10); int num = a.getNum();
    }
}


In C #, in order to simplify operations, a concept of attributes is introduced, for example:


 
class A
{ public int num { get; set; }
} class B
{ public void test()
    {
        A a = new A();
        a.num = 10; int re = a.num;
    }
}


In Class A, a property, NUM, is defined in Class B, which is accessible directly through the property name, simplifying the syntax in Java.
When you define num in a, you can have only a get or set token, which indicates read-only or write-only.



There is a problem with the method above, if you need to return a value by a certain calculation in a GET or set operation, you can use the following code. The calling method does not change.


 
class A
{ private int _num; public int num
    { get { return _num; } set { _num = value*2; }
    }
}


Compared to the above, a common variable _num is defined (this is private and does not allow direct external access).
It then defines a property, num, with the corresponding code, where value in the set code is an implicit parameter, which is the parameter passed in when the value is set to the property.



This is similar to the way Java code is used, except that it eliminates the need to define setxxx-like methods. In addition, the invocation is simplified, directly through the property name.






2. Access modifiers



In Java, there are public, protected,private, and default four-level modifiers, which are default when defining classes and members without modifiers.



In C #, the default modifier needs to be displayed with the internal keyword, and if defined without a modifier, the default is not internal but private. And in C #, you can use the protected internal combination, which means accessing a derived class that is limited to that class or the current assembly (the same namespace). The separate protected range is larger than the protected internal, and the allowed derived classes are not limited to the current assembly, plus the internal restricts the derived class to the current assembly.






3. Inheritance syntax for classes



Both support class inheritance, support for multiple parent classes in C + +, simplified in C #, and, like Java, only one parent class is allowed.



In Java, the class is inherited through the extends keyword, and in C # The syntax for C + + is represented by a parent class followed by: The processing mechanism of the parent class constructor is also different. The following examples illustrate.



The following code is an example of Java:


class A {
     private int num;
     public A (int num) {
         this.num = num;
     }
}

class B extends A {
     public B (int num) {
         super (num);
         // Other code, the super statement must be placed on the first line.
     }
} 


As you can see, use the extends keyword in Java to inherit the parent class, and use the Super method to invoke the parent class's constructor.



Here's the code for C #


 
class A{ private int num; public A(int num){ this.num = num;
    }
} class B : A{ public B(int num):base(num) {

    }
}


As you can see, the parent class is inherited through the: identifier in C #, and the parent class constructor is invoked through the base keyword.



4. Interface



In Java, an interface type is introduced, and a class can implement one or more interfaces.



In C #, reference Java introduces the mechanism of the interface, noting that there is no interface mechanism in C + +.



However, there are some differences in the syntax for implementing interfaces, which are identified by the Implements keyword in Java, and in C #, as with inheritance.



Here is an example of Java syntax


interface hello1 {}
interface hello2 {}

class A implements hello1, hello2 {
     private int num;
     public A (int num) {
         this.num = num;
     }
}

class B extends A implements hello1, hello2 {
     public B (int num) {
         super (num);
         // Other code, the super statement must be placed on the first line.
     }
} 


In Java, when a class needs to inherit both the parent class and the implementation interface, the extends statement is placed before the implements statement.



The following is a C # syntax example


interface hello1 { } interface hello2 { } class A:hello1,hello2{ private int num; public A(int num){ this.num = num;
    }
} class B : A,hello1,hello2{ public B(int num):base(num) {

    }
}


In C #, when a class needs to inherit both the parent class and the implementation interface, because it is followed by: The parent class name needs to precede, the interface name is followed, as in the example above.



5. Reload, override (polymorphic)



The so-called overload is that a class can have multiple methods, like the method name, but the parameter information is different. This is supported by both Java and C #.



Rewriting is the embodiment of polymorphism in object-oriented programming. That is, subclasses can define methods that are the same as the parent class, executing the parent class method or the subclass method dynamically, depending on the instance binding. Both Java and C # have this feature, and the difference is that there are some differences in syntax.



Examples of Java:


package com;

public class Demo {
     public static void main (String [] args) {
         A a = new A ();
         a.show (); // The output is i am A

         B b = new B ();
         b.show (); // The output is i am B

         A c = new B ();
         c.show (); // The output is i am B. Polymorphic manifestation, dynamic decision to call the parent or child method. Because c actually points to instance of B
     }
}

class A {
     public void show () {
         System.out.println ("i am A");
     }
}

class B extends A {
     public void show () {
         System.out.println ("i am B");
     }
} 


As you can see, subclass B overloads the method of parent Class A by defining the same method. When actually executed, the call is a method of the parent class or subclass, depending on the specific instance that the variable points to.



C # example, C # 's syntax in polymorphism refers to the features of C + + and needs to be identified by the virtual and override keywords.


class Myapp
{
     private static void Main (string [] args)
     {
         A a = new A ();
         a.show (); // The output is i am A

         B b = new B ();
         b.show (); // The output is i am B

         A c = new B ();
         c.show (); // The output is i am B. Polymorphic manifestation, dynamic decision to call the parent or child method. Because c actually points to instance of B
     }
}

class A {
     virtual public void show () {
         System.Console.WriteLine ("i am A");
     }
}

class B: A {
     override public void show () {
         System.Console.WriteLine ("i am B");
     }
} 


As you can see, in C #, to achieve the polymorphism of inheritance, you need to identify it with the virtual keyword in the parent class method, and then use the Override keyword in the method of the subclass.



It is important to note that for a virtual or non-vritual method defined by the parent class, the subclass can not be overloaded, but the same method can be defined (without the override keyword), which is allowed, when the method of the subclass hides the method of the parent class, which is not a dynamic attribute.






6. Abstract classes and abstract methods



Sometimes an ordinal method is defined in the parent class, but the method does not need to have a concrete implementation in the base class and needs to be implemented in the subclass. This feature is supported in both Java and C #.



There is only a slight difference in grammar. Here is an example of this.



Examples of Java:


package com;

public class Demo {
     public static void main (String [] args) {
         B b = new B ();
         b.show (); // The output is i am B

         A c = new B ();
         c.show (); // The output is i am B. Polymorphic manifestation, dynamic decision to call the parent or child method. Because c actually points to instance of B
     }
}

abstract class A {
     public abstract void show ();
}

class B extends A {
     public void show () {
         System.out.println ("i am B");
     }
} 


In Java, abstract classes and abstract methods are identified by the abstract keyword, with the following specifics:
1) A class has an abstract method, and the class in which it resides must be defined as an abstract class.



2) subclasses inherit the abstract parent class, either implement the abstract method of the parent class, or continue to define themselves as abstract classes.



3) There is no method body for abstract methods. Abstract classes cannot be instantiated.



The following is an example in C #


class Myapp
{
     private static void Main (string [] args)
     {
         B b = new B ();
         b.show (); // The output is i am B

         A c = new B ();
         c.show (); // The output is i am B. Polymorphic manifestation, dynamic decision to call the parent or child method. Because c actually points to instance of B
     }
}

abstract class A {
     abstract public void show ();
}

class B: A {
      override public void show () {
         System.Console.WriteLine ("i am B");
     }
} 


In addition to the subclass method definition requires the Override keyword, other syntax requirements are the same as in Java. In addition, the requirements for abstract and abstract methods are consistent with those in Java.



third, other comparisons



1. Constants and read-only fields



In Java, you can define read-only variables by final, and you can make member variables, which can be local or formal parameters within a method. and the definition and initialization can be together, can also be separated.



If the final member variable is defined, it needs to be initialized in the constructor. If it is a local variable within a method, you can assign a value after the definition.



In C #, you can define constants with the Const keyword, which requires that assignments must be understood at the time of definition.



In C #, you can also use ReadOnly to define a member of a class (note that you cannot define a local variable), you can assign a value when you define it, you can define it without assigning a value, and you assign a value in the constructor.






2. Exception handling



Java and C # have similar exception handling mechanisms and syntax, all with the use of try, catch, finally, throw, and several keywords. The difference is:



1) Exceptions in Java are categorized as check-in exceptions and run-time exceptions, whereas in C # there is only one (run-time exception).



2) in Java, the catch statement must have an exception type parameter.



In C #, it can be done without, indicating that it is the default, representing all exception handling, but if more than one exception is defined, it must be placed at the end without parameters.






3. Parameter passing



In Java, parameter passing is only a way of passing values. For basic data types, such as int, you cannot modify the value of a method within a method.



In C #, however, the features of C + + are preserved, and by using the ref and outer keywords, the parameters and arguments can be pointed to the same value, so that the values of the parameters are modified within the method, and the argument values outside the method change accordingly.



However, to improve the readability of the program, it is recommended to use this feature sparingly.






4. Inner class



In Java, internal classes are supported, including anonymous inner classes. In C #, however, internal classes are supported, but anonymous inner classes are not supported.



The following anonymous inner classes are allowed in Java, but not in C #.


package com; public class Demo { public static void main(String[] args) {
        A a = new A() { public void show() {
                ;
            }
        };
        a.show();
    }
} abstract class A { public abstract void show();


5. Partial class



In C #, when you write code, you can divide the definition of a class into multiple CS files, which are subsequently automatically merged by the compiler. This is not supported in Java.



This feature is not very good and it is strongly recommended that you do not use it under normal circumstances.






A contrastive analysis of C # syntax and Java syntax


Related Article

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.