[Java] _ 2_java course 6

Source: Internet
Author: User

I don't know whether it is an ESET problem or a developer problem. I have listened to the players downloaded from the official website of Youku, Baidu audio and video downloaded from Baidu, and iku software downloaded from Youku.

ESET reports potential threats. This software is easy to write and does not know when the software will work normally.

In the past few days, because of the company's business, I was too busy to update the text in time. Today, I am off duty, so I went to the garden and continue my java journey.

Describes some basic java points. Today we will discuss OOP in Java.

[OOP]

Oop? What is oop? To be honest, I don't understand it. I don't think there is a complete, very strict definition. The concept of OOP needs to be described, not a simple definition.

You can understand.

Oop: Object-oriented programming, which emphasizes the concept of "object". What is object? If you are familiar with the concepts of UNIX files, you should understand

The fact is that everything in UNIX is a file. Here, we can promote a similar concept: In the OOP world, everything is an object. That is to say, anything

Everything can be abstracted as an object, which is a bit of dialectical philosophical meaning and a little of methodological adjustment. programmers do not need to grasp this concept, and programmers need

Understand various features of OOP: encapsulation, inheritance, and polymorphism.

[Encapsulation]

The purpose of encapsulation is to hide from the cat and prevent any instance domains and methods in the category.

Encapsulation: encapsulation is an important feature of OOP. It is a bit like hiding in the cat, and it also means "golden house, Tibetan Jiao". This "jiaowa" will also give it to the popular second milk.

You are in trouble. The purpose of encapsulation is not to let you know the specific internal implementation.

In terms of encapsulation, data and operation behaviors are coupled together, and internal implementations and structures are not disclosed to the user of the object, but an interface is provided to the user,

Users can use objects correctly as long as they know the interface specifications.

The encapsulated object data is called an instance domain, and the process of operating data (sometimes a function) is called a method.

The main point of encapsulation is that the object method cannot directly access other class instance domains.

[Inheritance]

The purpose of inheritance is to improveCode.

Inheriting this concept or this theory does not know whether it is related to biology. I have been confused when I have read a lot of materials and have not mentioned this problem, because there are many problems in nature.

Things are the object of human science and technology imitation. Maybe this is also related.

Inheritance is similar to genetic inheritance. Hypothetical Class A is the parent class (or the base class), and Class B is the subclass (or the extension class ), in this way, Class B has all the features of Class.

Just like the inheritance of genes, the son inherits the father's genes. Generally, when designing child classes, we will not be completely the same as the parent class, which is similar to the variation of genes; if

Class B also inherits Class C, which is similar to the son's inheritance from the mother's genes, but unfortunately, Java does not allow multiple inheritance (tragedy, c ++ allows many repeated inheritance, Java

Sub-classes in are destined to be children of a single-parent family). To implement multi-inheritance, other mechanisms are required. It seems that the interface mechanism can be implemented.

[Polymorphism]

What is the purpose of polymorphism? The purpose of polymorphism is to improve the applicability of interfaces.

What does polymorphism mean? There is no suitable analogy, but there is a scenario suitable to illustrate this problem: in C language, calculate the maximum or minimum values of two numeric functions.

Exp:

IntIMAX (IntIvaluea,IntIvalueb ){ReturnIvaluea> ivalueb?Ivaluea: ivalueb ;}

We can see that, due to type restrictions, I cannot use this function to calculate the maximum value of a realistic number. to calculate the maximum value of a realistic number, we must write a function similar to a function.

In addition, we have to design a new name for the real number function, and the problem arises. In the process of using it, we hope it is a function name that can be used to evaluate the greatest value of the int type,

At the same time, it can also be used to calculate the maximum value of the number, so that users do not have to worry about whether the function name is correct, we only need to use a Unified Call format.

Here, we want the most value function to be like this: the_max_value = max (valuea, valueb); the call format can meet both the int type and

Float Type. We do not need to care about the data type of the input parameter. This is not realistic in the C language, and OOP can easily implement this requirement. In C ++

Function Overloading is easy to implement. This means we can define it like this:

Max (INT valuea, int valueb); // method 1

Max (double valuea, double valueb); // method 2

We can use the_max_value = max (valuea, valueb) when calling. During the runtime, method 1 or

Method 2.

There are many differences between Polymorphism in Java and C ++. For example, operators can be overloaded in C ++, but operators cannot be overloaded in Java (the characters mentioned earlier

Concatenation operator + is not the result of operator overloading, although the two seem very similar ).

[OOP Summary]

The above discussions are all about the scope of methodology, and there is no specific implementation involved. This requires attention and the idea determines the train of thought.

Class and Object]

Everyone should have seen the plastic porcelain bodhisattva. The craftsman has a plastic mold, and then there will be gypsum powder that has been stirred up. When we want to shape the porcelain Bodhisattva, the craftsman

After the model is made into the form of a Bodhisattva, the model is taken down as a Bodhisattva.

The class here is the model, the object is the molded Bodhisattva, And the gypsum powder is the memory space.

Object]

To use one thing, this thing must exist; otherwise it will be a mirror.

The same is true for objects. To use objects, objects must be stored first. How does an object come from Java?

In Oop, the constructor is used to construct objects. People who have been in contact with C ++ should know that in C ++, constructor is a class constructor. In Java, there must also be

Constructor to construct objects.

In Java, the constructor is a public method of the class. The constructor must be consistent with the class name. The constructor is used to instantiate an object and set the initial state of the object.

The constructor method can have parameters or no parameters.

When instantiating an object using the constructor method, you need to apply for memory space from the system. The process of applying for space is completed by the new operator. For example, there is a date class in the Java built-in library,

If we need to construct a date object, as shown below:

 
NewDate ();

Here we have constructed a date object, but in this case, we will not be able to use this date object in the future.

Of course, if the object only needs to be used once, we can do this:

 
String datestr =NewDate (). tostring;

Here we use the tostring method of this object.

If you want to use this object multiple times after constructing an object, you need to define an object variable. Use object variables to reference the constructed object. As follows:

As shown in:

Date birthday; // defines an object variable of the date class. This object variable is allocated with memory space, but this memory space is not the memory space required by the date object.

Birthday = new date (); // associate birthday with the newly constructed date object. At the same time, the new operator applies to the system for a space to represent the date object.

Here we need to distinguish between the birthday object variable and the date object. Shows their relationship:

The reference here is a little similar to the reference in C ++, but the difference between the reference and the object variable needs to be distinguished. In C ++, there is no blank reference, and references in C ++ cannot be assigned multiple times;

That is to say, after being referenced in C ++, it cannot be changed. In Java, object variables can be changed and pointed.

Key points:

The object variable is not the object itself, and the object variable can be used only after the object is initialized.

 
Date birthday; string Str= Birthday. tostring ();//Compilation Error

This error occurs because the object variable can be referenced only after the object is initialized. There are two methods to initialize object variables.

Exp:

 
Date Birthday =NewDate (); date deadline; deadline= Birthday;

The Relationship Between birthday and deadline is shown in:

Key points:

[Empty object]

In Java, there is a predefined object null-null object.

It can be displayed to set an object variable to null. An object variable set to null indicates that no object is referenced. If you call the method of setting an object variable to null, it is equivalent to referencing an empty object,

By referencing an empty object,RuntimeError.

Exp:

 
Date Birthday =Null; System. Out. println (birthday. tostring ());//Will generate a runtime error

[Object Storage space]

We will not discuss this issue for the moment. After we have discussed the topic of OOP, we will discuss the content of object space allocation.

[Change method and accessors method]

We know the information of the object stored in the instance domain in the class, and the method is used to operate on the instance domain. Here we generally call the method for reading the instance domain information the accessor method;

The method for modifying the instance domain is called the modifier method.

The purpose of designing the modifier method and accessors method is to support the encapsulation features of objects (or classes.

To modify or obtain the instance domain of a class, we usually recommend that you use the modifier method or accesser method to ensure the validity of instance domain access.

Although we can define a public instance domain, we do not recommend that you do this. For encapsulation, we recommend that you use the modifier method and accesser method.

Design an employee]

What information should employees include?

1. Name

2. Gender

3. Phone number (telphone number)

4. Salary

As mentioned above, to instantiate an object, there must be a constructor, so the employee class must have at least one constructor method.

1. employee ();

To obtain employee information and modify employee information, we must also have the modifier method and accesser method.

1. getname;

2. getgender

3. getphonenumber

4. getsalary

5. setname

6. setgender

7. setphonenumber

8. setsalay

After we obtain the information, we sometimes need to print it out and view it. This requires printing related methods.

1. printname

2. printgender

3. printphonenumber

4. printsalary

 

[Code style]

The code sequence does not affect the design class.ProgramBut in actual operation, different people will have different styles,

For example, some people like this design:

Class classname

{

Field1;

Field2;

.....

Construct Method1;

Construct method2;

.....

Method1;

Method2;

.......

}

 

Some people like this design:

Class classname

{

Construct Method1;

Construct method2;

.....

Field1;

Field2;

.....

Method1;

Method2;

.....

}

Some people like this design:

Class classname

{

Construct Method1;

Construct method2;

.....

Method1;

Method2;

.....

Field1;

Field2;

.....

}

I personally think that it doesn't matter which style is used. What is important is to maintain consistency during code editing so that it won't bring about code maintenance and upgrade in the future.

Too much trouble.

However, the author of the book I read now prefers the third style. The author thinks that:

Using this style will prompt the class designer to design the class before deciding to write the code when the code is not edited.

Half of the time suddenly remembered the need to add an instance domain or suddenly remembered the need to add a method, this long time is conducive to improving the practical ability of the programmer's design class.

 

[Code]

The following is the design code. It is not completed due to time.

 /*  Design employees  */  Class  Employee {  Public Employee (string inname,Boolean Ingender, string inphonenumber, Double  Insalary ){  If (! Setname (inname) {} setgender (ingender); setphonenumber (inphonenumber); setsalary (insalary );}  Public  String getname (){  Return  Name ;}  Public   Boolean  Getgender (){  Return Gender ;}  Public  String getphonenumber (){  Return  Phonenumber ;}  Public   Double  Getsalary (){  Return  Salary ;}  Public   Boolean  Setname (string inname ){  If (Inname. Equals ("") {System. Out. println ( "You haven't enter you name" ); Retrun  False  ;} Name = Inname ;}  Public   Boolean Setgender ( Boolean  Ingender ){}  Public   Boolean  Setphonenumber (string inphonenumber ){}  Public   Boolean Setsalary ( Double Insalary, Boolean  Raise ){}  Public   Void  Printname (){}  Public   Void  Printgender (){}  Public   Void  Printphonenumber (){}  Public   Void  Printsalary (){} Private  String name;  Private   Boolean  Gender;  Private  String phonenumber;  Private   Double  Salary ;} 

Haha, the code will be incomplete at the next time, and there is something to be discussed here.

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.