Java attack C #-object-oriented syntax,

Source: Internet
Author: User

Java attack C #-object-oriented syntax,

Summary of this Chapter

In the previous chapter, I learned about ADO. NET and how to access the database. This chapter will introduce the object-oriented thinking in the future. Whether in JAVA or in C #, the importance of Object-oriented thinking is a major component. It is often like breathing, and we will ignore it more often. Object-Oriented Programming has three main features: encapsulation, polymorphism, and inheritance. I will not introduce the definition of these three features too much. An article similar to this on the internet is searched. I believe there must be something you need. The main objective of this series is to allow JAVA programmers to enter the C # development environment. Therefore, we will explain the differences between the two.

Class and Object

Before explaining the object-oriented thinking, I think we should first understand what is class, what is object, and the relationship between them. In this way, we can better understand the object-oriented thinking. Searching related classes and objects on the Internet is also a large piece of information. I don't want to explain it too much. I just wrote my own understanding, hoping to help you. I usually like to understand the class as the house structure drawings used when building a house. The object is the house built successfully according to the house structure drawings. The drawings here are. cs files, and the structure above the drawings is a class. A successful house is an object, that is, an instance in the memory. This is my understanding. With this one, let's take a look at the three major features.

Object-oriented Encapsulation

This is what I see in the encapsulation. If there is a process-oriented development, the readers will understand. The so-called encapsulation is to put the relevant data in the same region, and then give the region a name. In this way, you can know the source in future development. The "." In the code is the best proof. I don't want to talk about how useless it is. We will learn in the form of code. As follows:

C #:

 1  public class Person 2     { 3         public string Name { set; get; } 4  5         public string Sex { set; get; } 6  7         public void Move() 8         { 9  10         }11     }

The author defines a class called Person. Obviously, the biggest difference lies in the "{set; get;}" part of the code. I believe that in JAVA, we often see some customary writing methods. Forget it. For the convenience of reading the author, write the code and paste it out.

JAVA:

 1 public class Person { 2      3     private String name; 4     private String sex; 5      6     public String getName() { 7         return name; 8     } 9     public void setName(String name) {10         this.name = name;11     }12     public String getSex() {13         return sex;14     }15     public void setSex(String sex) {16         this.sex = sex;17     }18     19     public void Move()20     {21         22     }23     24 }

We can see that if the JAVA side wants to use internal members outside the class, it must be implemented through the corresponding set or get method. In C #, this is not the case. He has his own concept of attribute. The above C # code is the writing of attributes. But he is still abbreviated. To learn more, let's take a look at the writing method.

C #:

 1 public class Person 2     { 3         private string _name; 4         private string _sex; 5         public string Name  6         { 7             set { this._name = value; } 8             get { return this._name; }  9         }10 11         public string Sex12         {13             set { this._sex = value; }14             get { return this._sex; }15         }16 17         public void Move()18         {19  20         }21     }

The above code is the complete writing of the C # attribute. However, C # developers tend to dislike it. We also know that JAVA may make some judgment or processing when assigning values to internal member variables of the class. Corresponding C # Here you can see that the braces behind the set are missing. It is written in braces. The keyword value is the value that will be passed out in the future. The Code is as follows:

C #:

1 public string Name 2 {3 set 4 {5 if (string. IsNullOrWhiteSpace (value) // you can check whether the passed value is null. These include space Key 6 throw new ArgumentNullException ("the name cannot be null"); 7 this. _ name = value; 8} 9 get {return this. _ name;} 10}

C # Use of attributes:

Person person = new Person();person.Name = "Aomi";person.Move();

When constructing a class, we often define a member called a constant. JAVA is implemented with the keyword final. C # uses the keyword const. Of course, there is also a keyword readonly. In a sense, it is similar to a constant. But it cannot be a constant. It can only be a read-only variable member. And the two of them have a big difference when assigning values. As follows:

Keyword const: assign a value when defining the const.

Keyword readonly: It must be assigned a value during definition. In the constructor at the same time.

C #:

private readonly string Nick ="aaa";public const string DefaultName = "Person";

In addition to the assignment and definition, you can also understand that they are different in use. The const keyword is used by classes. For example, Person. DefaultName. However, the keyword readonly is internal to the object. Note This.

When we encapsulate data into a class, we must deal with the class constructor to use this class. This is a big difference from JAVA. The following code

C #:

 public Person():this("Aomi") {           } public Person(string name) {     this.Name = name; }

From the above code, we can understand that JAVA is written in the constructor. C # is behind the function name. Note that ":" is added.

Object-oriented Inheritance

For inheritance, most of them are no different from JAVA. Both extends and implements must use. This is a little simpler than JAVA. It is worth noting that it is related to the constructor. We all know the super keyword of JAVA. C # uses the base keyword. At the same time, the usage is different. As follows:

public class Child : Person    {        public Child()            : base("Aomi")        {         }    }

After thinking for a while, I think there is no difference in inheritance.

Object-oriented Polymorphism

I personally think JAVA may be easier to understand in terms of polymorphism. Why? We know that polymorphism is divided into rewriting and overloading. The biggest difference is rewriting.

1. Reload. This is what a versatile user means. The syntax is the same as that of C. The method name must be the same, but the parameter type or number is different.

2. rewrite. It is the same as JAVA. But there is a big difference in writing.

C # Person class:

1 public class Person 2 {3 4 private string _ name; 5 private string _ sex; 6 public readonly string Nick = "aaa"; 7 public const string DefaultName = "Person "; 8 9 public Person (): this ("Aomi") 10 {11 12} 13 public Person (string name) 14 {15 this. name = name; 16} 17 public string Name 18 {19 set 20 {21 if (string. isNullOrWhiteSpace (value) // determines whether the passed value is null. Including Space key 22 throw new ArgumentNullException ("the name cannot be null"); 23 this. _ name = value; 24} 25 get {return this. _ name;} 26} 27 28 public string Sex29 {30 set {this. _ sex = value;} 31 get {return this. _ sex;} 32} 33 34 public void Move () 35 {36 Console. writeLine ("person move"); 37} 38}

C # Child class:

 1    public class Child : Person 2     { 3         public Child() 4             : base("Aomi") 5         { 6   7         } 8         public void Move() 9         {10             Console.WriteLine("child move");11         }12     }

C # Program class:

 class Program    {        static void Main(string[] args)        {            Person person = new Child();            person.Name = "Aomi";            person.Move();        }    }

Execution result:

The execution result of the above Code is: person move. The Child class overrides the Move method of the Person class and encapsulates the Child class instance with the Person class. I used similar functions to perform experiments in JAVA and found that the execution result is: child move. In C #, three keywords are involved: virtual, new, and override. In the above C # code, the Move method of the Child class is actually public new void Move (). That is to say, the method of the original parent class is not overwritten. Therefore, the Person class method is executed when the Person class is used to wrap the Child class instance. So the C # rewrite usage. It should be like the following.

C # Person class:

public class Person{     public virtual void Move()     {            Console.WriteLine("person move");     }}

C # Child class:

 public class Child : Person    {        public override void Move()        {            Console.WriteLine("child move");        }    }

See it. If the parent class has methods that may be overwritten in the future, it is best to use the keyword virtual to modify this method. To override the parent class, the subclass must use the key override. The key new is to re-subclass and write a method without affecting the parent class.

Summary

This chapter focuses on some aspects that should be understood when Object-Oriented Programming in C. We can see that there is little difference in inheritance. There are still some differences between encapsulation and polymorphism. The same is the difference in constructor.

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.