Method rewriting and method overloading; Method Rewriting Method Overloading

Source: Internet
Author: User

Method rewriting and method overloading; Method Rewriting Method Overloading

Inheritance and polymorphism are the characteristics of object-oriented programming. Using inheritance, you can create a subclass based on a parent class. This subclass not only has the existing attributes and methods of the parent class, but also can create its own attributes and methods. The relationship between subclass and parent class leads to the problem of method rewriting and method overloading. There are many problems in the application of inheritance and Polymorphism in method rewriting and method overloading. These concepts are easy to confuse, understanding the differences between rewriting and overloading lays the foundation for learning to write programs using polymorphism and improving the maintainability of programs.

I. Method rewriting (0 veriding)
How to define Rewriting: In a Java program, the inheritance relationship of classes can generate a subclass that inherits the parent class and has all the features of the parent class, inherits all methods and variables of the parent class. Child classes can define new features. When child classes need to modify some methods of the parent class to expand and increase functions, programmers often refer to such an operation method as rewriting, it is also called overwrite or overwrite. Rewriting reflects the advantages of Java
Rewriting is based on the inheritance relationship, which makes the language structure richer. In Java inheritance, subclasses can hide and access methods of the parent class, or override methods that inherit the parent class. The method that overwrites the parent class in Java is implemented through method rewriting.

Method rewriting means that the method in the subclass has the same return value type, Method Name, number of parameters, and parameter type as the method inherited in the parent class. In this way, the parent class method can be overwritten. For example, the following code overwrites the method.


Class Person // defines the parent class
Fpublic void print () {// method in the parent class
System. out. println (print method of the parent class Person! );
}
}
Class Student extends Person // defines the subclass to inherit the Person class
{Public void print () {// rewrite Method
System. out. println (subclass Student's print method! );
}
}
Public class 0verrideExampleO1
{Public static void main (String args [])
{Student s = new Student ();
S. print ();
}
}

Running result: print method of Student!

It can be seen that when the subclass overrides the print () method in the parent class, S is used to call the print () method of the subclass, and the print () method in the parent class is overwritten. That is to say, if the child class overrides the methods in the parent class and the called method must call the method that has been overwritten, what should I do if I must call the methods in the parent class now? In this case, you can use .. super can achieve this function. The super keyword can access the content in the parent class from the subclass. If you want to access the method that has been overwritten, use "super. method Name (parameter list.

For example:
Class Person
{Public void print (){
System. out. println (print method of the parent class Person! );
}
}
Class Student extends Person
{Public void print (){
Super. print (: // method used to access the quilt class overwrite in the parent class
System. out. println ("subclass Student's print method! ");
}
}
Public class OverrideExample02
{Public static void main (String args [])
{Student s = new Student ();
S. print ();
}
}
Running result: print method of the parent class Person!
The print method of the subclass Student!
If you want to use the super keyword, you do not have to use it after method rewriting,

It can also explicitly indicate that a method is inherited from the parent class. Use super

It is just more explicit that, to search from the parent class, it will not be found in the subclass.

Ii. Rewrite Rules
When rewriting a method, follow the following rules:

(1) The parameter list of the parent method must be the same as the parameter list of the method that is overwritten by the quilt class. Otherwise, it cannot be called an overwrite but an overload...
(2) The return type of the parent class must be the same as that of the method rewritten by the quilt class. Otherwise, it cannot be called an overwrite but an overload...
(3) Java stipulates that the quilt class override method cannot have more strict access permissions than the parent class method. The access permission relationship is as follows:

The person who has compiled the Java program knows that the methods in the parent class can not be overwritten under any circumstances. When the access permission modifier of the methods in the parent class is private, this method can only be accessed by its own class. It cannot be accessed by external classes and cannot be overwritten in subclass. If the method for defining the parent class is public and the subclass is private, an error is reported when the program runs. For example:

Class Person
{Public void print () (// public access permission
System. out. println ("print method of the parent class Person! ");
}
}
Class Stedent extends Person
{Private void print () (// rewrite method reduces the access permission, error
System. out. println ("subclass Student's print method! ");
}
}
(4) because the access permission modifier of the parent class must be greater than the access permission modifier of the quilt override method, the private permission is the least. Therefore, if the access permission of a method in the parent class is private, it cannot be overwritten in the subclass. If a new method is defined, it will not be overwritten.

(5) If the method in the parent class throws an exception during the inheritance process, an exception will also be thrown when the parent class is rewritten in the subclass, in addition, the exception cannot be more than the exception thrown in the parent class (which can be equal to the exception thrown in the parent class ). In other words, the rewrite method must not throw a new check exception, or a more general check exception than the declared method. For example, a method of the parent class declares an IOException check. When you override this method, you cannot throw an Exception. You can only throw a subclass Exception of IOException, but can throw a non-check Exception.


Similarly, if a member variable is created in the subclass
A variable in the parent class has the same name, which is called variable rewriting or attribute overwriting. However
The concept is rarely studied, because it is of little significance.

3. Method Overloading)

(1) how to define overload. Method rewriting and overloading are only one word different. Many beginners think the two are very similar, but they are not. Method Overloading is a means for classes to process different types of data in a unified manner. When a method is called, different numbers and types of parameters are passed to them to determine which method to use. This is polymorphism.
Method overloading means that in a class, multiple methods have the same method name but different parameter lists. The parameter list varies with the number, type, or order of parameters. Method Overloading is also frequently used in practical applications. It is not only a common method, but also a constructor. The following example is used for analysis.
Overload definition and usage.

Class Person {
{String name;
Int age;
Void print (){
System. out. println ("name:" + name + "age:" + age );
}
Void print (String a, int B ){
System. out. println ("name:" + a + "Age:" + B );
Void print (String a, int B, intC ){
System. out. println ("name:" + a + "Age:" + B + "ID:" + c );
}
Void print (String a, int B, doubleC ){
System. out. println ("name:" + a + "Age:" + B + "ID:" + c );
}
}

Public class OverLoadExampleOL
{Publicstaticvoidmain (String args [])
{Personpl = newPerson ();
P1.nanle = "Li Ming ";
P1.age = 22;
P1.print ();
P1.print ("Wang xiaozao", 19 );
P1.print ("Jin Bo );
P1.print ("Wanning );
}
}

In the above program, we can see that there are multiple methods named void print in the Person class, which is the overload of the method. Run the program as follows:

Name: Li Ming age: 22
Name: Wang xiaozao age: maid
Name: Jin Bo age: 18ID: 10 00325
Name: Wanning age: 25ID No.: 110903

There must be a certain relationship between methods during method overloading, because this can improve the readability of the program. Generally, only methods with similar functions are overloaded. Overload means that we can define methods with the same name. Different parameters are defined to distinguish these methods. Then, when you call them again, the Java Virtual Machine will
Select an appropriate method for execution based on different parameter lists. That is to say, when an overloaded method is called, Java uses the parameter type and the number of. (OR) to determine the actually called overloaded method. Therefore, the type or number of parameters for each overload method must be different. Although each overload method can have different return types,
However, the return type does not determine which method is used. When Java calls an overloaded method, the method that matches the called parameter is executed. Pay attention to the following points when using overload:

1. When using overload, you can only use different parameter lists and must have different parameter lists. For example, different parameter types, different parameter numbers, and different parameter order. Of course, several parameter types in the same method must be different. For example, it can be fun (int, float), but not fun (int, int ).
2. It cannot be overloaded by access permission, return type, or thrown exception.
3. The exception type and number of methods will not affect the overload...
4. There can be different return types, as long as the parameter list is different.
5. Different access modifiers are available.

6. Different exceptions can be thrown.

Iv. Differences between method rewriting and method Overloading
Through the analysis in the above example, we can compare the differences between method rewriting and overload.
Form a table as follows:

Differences

Heavy Load

Rewrite (overwrite)

English

Overloading

Overiding

Definition

The method name is the same, and the type or number of parameters are different.

The method name, parameter type, and return value type are all the same

No permission required

The method to be rewritten cannot have more strict permissions.

Range

Occurs in a class

Occurs in the inheritance class

 

V. Conclusion
In the idea of object-oriented programming, the inheritance and Polymorphism of classes are mainly embodied in the method of rewriting parent classes by subclass. As a typical exception of method overloading, the overload of constructor can express multiple initialization behaviors of objects through the overload constructor. Flexible Method rewriting and method overloading can not only reduce the coding workload, but also greatly improve the maintainability and scalability of the program. Rewrite and reload
You can design a clear and concise class. It can be said that rewriting and overloading play an extraordinary role in coding.

References:
(1) Li Ning's method rewriting and method overloading in Java -- Science and Technology Information Publishing House
(2) Tan zhenjun's "Java core development technology from entry to mastery" -- Electronic Industry Press

Address: http://blog.csdn.net/zhangyabinsky/article/details/7047330

 

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.