Java syntax Summary-Method

Source: Internet
Author: User

I. Rewrite the method.

1. Rewriting can only appear in the inheritance relationship. When a class inherits its parent class method, it has the opportunity to override the method of the parent class. A special case is that the method of the parent class is identified as final. The primary advantage of rewriting is that it can define a behavior unique to a child type.
Class animal {
Public void eat (){
System. Out. println ("animal is eating .");
}
}

Class horse extends animal {
Public void eat (){
System. Out. println ("horse is eating .");
}
}

2. For an abstract method inherited from the parent class, you can either design the method by rewriting the subclass, or mark the subclass as abstract. Therefore, abstract methods must be rewritten.

3. Meaning of rewriting.
The override method can realize polymorphism and manipulate the subclass object with the reference of the parent class, but in actual running, the object will run its own unique method.
Public class test {
Public static void main (string [] ARGs ){
Animal H = new horse ();
H. Eat ();
}
}

Class animal {
Public void eat (){
System. Out. println ("animal is eating .");
}
}

Class horse extends animal {
Public void eat (){
System. Out. println ("horse is eating .");
}
Public void Buck (){
}
}

One principle is: when a reference is used, the compiler will only call the methods owned by the reference class. If the subclass-specific method is called, the H. Buck (); compiler in the example above will complain. That is to say, the compiler only looks at the reference type, not the object type.

4. Rewrite method rules.
If you want to implement a qualified override method, rather than overloading, you must meet the following requirements at the same time!

A. Rewrite Rules: the method to be rewritten cannot have a stricter access level than the method to be rewritten.
(But it can be more extensive. For example, the parent class method is the package access permission, and the override method of the subclass is the public access permission .)
For example, the object class has a tostring () method. When we start to rewrite this method, we always forget the public modifier. Of course, the compiler will not let us know any lessons. The cause of the error is that the method without any access modifier has the package access permission. The package access permission is stricter than the public permission, so the compiler reports an error.

B. Rewrite Rule 2: The parameter list must be the same as that of the method to be overwritten.
Rewrite has a twin brother called heavy load, that is, it will be coming soon. If the parameters of the subclass method are different from those of the parent class, you can identify the wrong person. This is an overload, not a rewrite.

C. Rewrite Rule 3: The return type must be the same as the return type of the method to be overwritten.
Parent class method A: void eat () {} sub-class method B: int eat () {} although the two parameters are the same, they return different types, so they are not overwritten.
Parent class method A: int eat () {} subclass Method B: Long eat () {} the return type is compatible with the parent class, but the difference is different, so it is not rewritten.

D. Rewrite Rule 4: the rewrite method cannot throw a new exception or a broader check exception than the check exception declared by the override method. However, you can throw fewer, more limited, or do not throw an exception.
Import java. Io .*;
Public class test {
Public static void main (string [] ARGs ){
Animal H = new horse ();
Try {
H. Eat ();
}
Catch (exception e ){
}
}
}

Class animal {
Public void eat () throws exception {
System. Out. println ("animal is eating .");
Throw new exception ();
}
}

Class horse extends animal {
Public void eat () throws ioexception {
System. Out. println ("horse is eating .");
Throw new ioexception ();
}
}
In this example, the parent class throws an exception check exception. The ioexception thrown by the subclass is a subclass of exception, that is, it throws a more limited exception than the overwritten method. If, in turn, the parent class throws an ioexception and the Child class throws a broader exception, it will not be compiled.
Note: This restriction only applies to check exceptions. The exception runtimeexception and its subclass are not limited.

E. Rewrite rule 5: The method marked as final cannot be rewritten.

F. Rewrite Rule 6: if a method cannot be inherited, it cannot be overwritten.
A typical example is the private method of the parent class. The next meeting will produce an interesting phenomenon.
Public class test {
Public static void main (string [] ARGs ){
// Animal H = new horse ();
Horse H = new horse ();
H. Eat ();
}
}

Class animal {
Private void eat (){
System. Out. println ("animal is eating .");
}
}

Class horse extends animal {
Public void eat (){
System. Out. println ("horse is eating .");
}
}
This code can be compiled. On the surface, it seems that the Sixth rule is violated, but it is actually a coincidence. The eat () method of the animal class cannot be inherited. Therefore, the Eat () method in the horse class is a brand new method, not a rewrite or overload, it's just a brand new method that only belongs to the horse class! This is confusing, but not so difficult to understand.
If the main () method is like this:
Animal H = new horse ();
// Horse H = new horse ();
H. Eat ();
The compiler reports an error. Why? The eat () method of the horse class is public! It can be called! Note that polymorphism only depends on the method referenced by the parent class, rather than the method of the subclass object!

Ii. Method overloading.
There is a good reload, it does not require you to convert the data type before calling a method, it will automatically find the matching method. The method overload decides which method to call at the time of compilation, which is different from rewriting. The most common part is the overload of the constructor.

1. overload of basic data type parameters.
Public class test {
Static void method (byte B ){
System. Out. println ("method: Byte ");
}
Static void method (short S ){
System. Out. println ("method: short ");
}
Static void method (int I ){
System. Out. println ("method: int ");
}
Static void method (float f ){
System. Out. println ("method: float ");
}
Static void method (double D ){
System. Out. println ("method: Double ");
}
Public static void main (string [] ARGs ){
Method (byte) 1 );
Method ('C ');
Method (1 );
Method ( 1l );
Method (1.1 );
Method ( 1.1f );
}
}
Output result:
Method: byte
Method: int
Method: int
Method: Float
Method: double
Method: Float

We can see that the first thing we need to find is the data type matching method. If no data type is found, it is upgraded to a data type with more expressive power. In the preceding example, the data type is not exactly the integer type of long, so it is converted to the float type. If the appropriate compatible type cannot be found through the upgrade, the compiler will report an error. It is not automatically converted to a smaller data type. You must force the conversion on your own to bear the consequences of the conversion.

The char type is special. If the matching type cannot be found, it will be converted to int instead of short, although char is 16 bits.

2. Reload method rules.

A. the parameter list must be changed for the overloaded method.
Parameters must be different. This is the most important thing! There are two differences: number of parameters, parameter type, and Parameter order.

B. the overloaded method has nothing to do with the return type.
That is to say, the return type cannot be used to distinguish the overload method.

C. The access modifier can be changed in the overloaded method.
There is no such strict restriction as the rewrite method.

D. The overloaded method can declare a new or broader check exception.
There is no such strict restriction as the rewrite method.

E. methods can be overloaded in a class or a subclass.

3. Method overload with object reference parameters.
Class animal {}
Class horse extends animal {}

Public class test {
Static void method (animal ){
System. Out. println ("animal is called .");
}
Static void method (horse H ){
System. Out. println ("horse is called .");
}
Public static void main (string [] ARGs ){
Animal A = new animal ();
Horse H = new horse ();
Animal Ah = new horse ();

Method ();
Method (h );
Method (AH );
}
}
The output result is:
Animal is called.
Horse is called.
Animal is called.
There is no problem with the first two outputs. Why isn't the third method output "horse is called? In the old saying, we should look at the reference type rather than the object type. Method Overloading is determined at the time of compilation, and the reference type determines which version of the overload method to call.

4. Summary of the differences between overload and rewrite methods.
If you can thoroughly understand the example below, it means that you have a good understanding of heavy load and rewrite, you can end the review of this section.
Class animal {
Public void eat (){
System. Out. println ("animal is eating .");
}
}
Class horse extends animal {
Public void eat (){
System. Out. println ("horse is eating .");
}
Public void eat (string food ){
System. Out. println ("horse is eating" + food );
}
}

Public class test {
Public static void main (string [] ARGs ){
Animal A = new animal ();
Horse H = new horse ();
Animal Ah = new horse ();

A. Eat ();
H. Eat ();
H. Eat ("apple ");
Ah. Eat ();
// A. Eat ("apple ");
// Ah. Eat ("apple ");
}
}

What are the four outputs? Why can't two comments be compiled?
Article 1: A. Eat (); common method calls, no polymorphism, no technical content. The eat () method of the animal class is called, and the output is animal is eating.
Article 2: h.eat (); common method calls have no technical content. The eat () method of the horse class is called, and the output is horse is eating.
Article 3: H. Eat ("apple"); reload. Two eat () Methods of the horse class are overloaded. The eat (string food) method of the horse class is called, and the output is: horse is eating apple
Article 4: Ah. Eat (); polymorphism. The previous example is not difficult to understand. Output: horse is eating.
Article 5: A. Eat ("apple"); low-level error. The animal class does not have the Eat (string food) method. Therefore, it cannot be compiled.
Article 6: Ah. Eat ("apple"); the key point is here. The solution is still the old saying, not the object type, but the reference type. The animal class does not have the Eat (string food) method. Therefore, it cannot be compiled.

Summary: Polymorphism does not determine which overload version to call. polymorphism takes effect only when determining which rewrite version to use.
During reload, the corresponding Runtime is overwritten. Concise enough!

3. Constructor.
Constructor is a special method. A new object cannot be created without constructor. In fact, we need to call not only the constructor of the actual object type, but also the constructor of its parent class to trace up until the object class. The constructor does not need to be explicitly called. When the new keyword is used, the corresponding constructor is automatically called.

1. constructor rules.
A. the constructor can use any access modifier. Including private. In fact, many Java class libraries are like this. designers do not want users to create objects of this class.

B. the constructor name must be the same as the class name. This makes the constructor different. If we follow Sun's coding rules, it seems that only the first letter of the constructor is capitalized.

C. The constructor cannot have a return type.
Conversely, the constructor does not have a return type.
Public class test {
Int test (){
Return 1;
}
}
What is this method? It's just a ghost posing as Li Yun. Int test () is no different from any other common method. It's just a normal method! It seems disgusting, but there are more disgusting things in the exam.

D. If you do not create your own constructor in the class, the compiler automatically generates the default constructor without parameters.
This is easy to verify! Write such a simple class and compile it.
Class test {
}
Decompile the generated test. Class file: javap test. You can see:
D: "javacode" bin> javap Test
Compiled from "test. Java"
Class test extends java. Lang. object {
Test ();
}
See the default constructor automatically added by the compiler!

E. If only a constructor with parameters is created, the compiler will not automatically add a constructor without parameters!

F. In each constructor, if the overload constructor this () method is used, or the constructor super () method of the parent class, the this () method or super () method () the method must be placed in the first line. The two methods can only select one, so there is no order between them.

G. Except for the constructor generated by the compiler, and the super () method is not explicitly called, the compiler inserts a super () Non-argument call.

H. abstract classes have constructor methods.

4. Static Method overloading and rewriting (overwriting ).

1. Static methods cannot be overwritten. We can discuss it in two situations:

A. The non-static method of the subclass "overwrites" the static method of the parent class.
In this case, it cannot be compiled.

Class father {
Static void print (){
System. Out. println ("in Father method ");
}
}
Class Child extends father {
Void print (){
System. Out. println ("in child method ");
}
}

The static method indicates that the method does not associate objects of a specific class. You can call the method directly through the class name, that is, it is bound at the early stage of compilation. There is no dynamic binding at the later stage, that is, it cannot implement polymorphism. The non-static method of the subclass is bound to a specific object, and the two have different meanings.

B. The static method of the subclass "overwrites" the static method of the parent class.
This overwrite is still enclosed by quotation marks. In fact, adding the static modifier before the print method of the Child class in the above example can indeed be compiled! But do not think this is a polymorphism! The characteristic of polymorphism is dynamic binding. See the following example:

Class father {
Static void print (){
System. Out. println ("in Father method ");
}
}
Class Child extends father {
Static void print (){
System. Out. println ("in child method ");
}
}

Class test {
Public static void main (string [] ARGs ){
Father F = new child ();
F. Print ();
}
}

Output result: In father Method
The result shows that there is no polymorphism.
However, this form is confusing and seems to be a multi-state. In actual programming, do not do this. It will make everyone confused!
It does not conform to the Features Shown in overwrite, and should not be overwrite!
All in all, static methods cannot be overwritten.

2. Static methods can be overloaded like non-static methods.
There are too many such examples, so I don't want to write a routine. Let's look at a lot of such examples in the Java class library.
For example, a bunch of overloaded binarysearch methods in the Java. util. arrays class.
Here I will mention it because I saw this when I checked the information. "Sun's sl275 course says that static methods can only control static variables (they do not), and static methods cannot be overloaded or overwritten ......"
Don't believe it! It can be reloaded. Static and non-static methods can be reloaded.

It is easy to understand from the overload mechanism that is determined at the Compilation Time. Non-static methods can be used. How can static methods not be used?

 

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.