Java BASICS (3)

Source: Internet
Author: User

1. Interface

An interface is a standard and a rule. It only shows the method and specifies which method you want to implement without providing the implementation of the method, let the interface implementation class implement these methods, but for different implementation classes, the implementation of methods can be completely different.

  If an interface implementation class implements an interface, all the methods to be implemented defined in the interface must be implemented. If you do not want to implement methods, the implementation class must be defined as an abstract class, and the methods you do not want to implement must be defined as abstract methods.

  The default access level of the attribute and method defined in the interface is public, so the method must not be modified by private. All methods contain abstract by default, indicating that it is an abstract method, but it can be omitted, and it is omitted by default.

  The interface is actually a dry abstract class. All the methods in it are abstract and cannot provide any implementation part.

  Because an interface is a special "abstract class", and because the abstract class can inherit other classes, the interface can also inherit interfaces or only inherit interfaces. However, the interface cannot be implemented.

  One class can implement multiple interfaces using the keyword implements. One interface can inherit multiple interfaces using the keyword extends. One class can inherit one class at the same time and implement one or more interfaces, however, the keyword extends must come first.

 

2. abstract classes and Methods

  • If an unpredictable method implementation exists in a method, the class of the method should be declared as an abstract class.  

• If there are methods of the same name in the two classes, it should be extracted to the parent class, but the two methods have obvious differences in implementation, then, the methods in the parent class should be defined as abstract and abstract methods. They only show the way the methods look, rather than the specific implementation of the methods, the specific implementation is implemented by inheriting the specific subclass of this class.

• Abstract methods must be in abstract classes. abstract classes do not necessarily have abstract methods.

• The existence of abstract classes without abstract methods is also meaningful. This determines that this class cannot be directly instantiated, and its function basically exists as a "box. ------------- Breeding pigs

• The premise of rewriting is that the parent class knows how to implement the method, and the subclass does not intend to follow the original path, so it overwrites the implementation in the parent class,

• The parent class does not provide implementation, nor does it know how to implement it. The specific subclass determines how to implement it. However, a definition must be provided for the subclass.

 

3. Differences between interfaces and abstract classes

  • Interfaces are implemented, while abstract classes are extends)

• An interface can inherit multiple other interfaces to form a new interface

• An abstract class can inherit one or more classes or implement one or more interfaces.

• The interface is a 100% abstract class, and no method in it has any implementation

• Abstract classes can contain non-abstract methods, that is, some methods can be implemented.

• Interfaces are generally at the bottom of the Code and some provisions are made. The abstract class layer above the interface implements the interface for the first time, making it impossible to complete the method at one time, it is implemented by its own subclass.

• Abstract classes can have constructor methods, but interfaces cannot have constructor methods. The variables defined in the interface can only be public, static, and final, and will be added by default.

 

4. Comparison between Java interfaces and Java Abstract classes

  1) The biggest difference between Java interfaces and Java Abstract classes is that Java Abstract classes can provide partial implementation of some methods, but Java interfaces cannot. This is probably the only advantage of Java Abstract classes, however, this advantage is very useful. If a new concrete method is added to an abstract class, all its subclasses will get this new method at once, and the Java interface cannot do this, if you add a new method to a Java interface, all classes that implement this interface cannot be compiled successfully, because you must make every class implement this method again, this is obviously a disadvantage of the Java interface.

  2) the implementation of an abstract class can only be given by the subclass of this abstract class. That is to say, this implementation is in the hierarchy defined by the abstract class. Due to the single inheritance of the Java language, so the efficiency of abstract classes as type definition toolsDiscounts. At this point, the advantages of the Java interface come out. Any class that implements the method specified by a Java interface can have the type of this interface, A class can implement any number of Java interfaces, so this class hasMultiple types.

  3) from the 2nd point, it is not difficult to see that the Java interface is an ideal tool for defining the hybrid type. The mixed class indicates that a class has not only a primary type but also other secondary behaviors.

  4) combined with the advantages of abstract classes and Java interfaces in and, the classic design mode came out: the Declaration type work is still undertaken by the Java interface, however, a Java Abstract class is provided and this interface is implemented. Other specific classes of the same abstract type can choose to implement this Java interface or inherit this abstract class, that is to say, in the hierarchy, the Java interface is at the top, followed by the abstract class. Ha, the biggest advantages of the two are all brought to the extreme. This mode is the "Default adaptation mode ".

  This mode is used in Java APIs and all follow certain naming rules: Abstract + Interface Name. Java interfaces and Java Abstract classes exist for implementation and Inheritance of specific classes. If you want to write a specific class to inherit another specific class, then there is a big problem with your design. The Java Abstract class exists for inheritance, and its abstract method is to force the subclass to be implemented.

 

5. Methods and code blocks

  Note 1. The local variables defined in a method cannot be declared as static. Static modifier static is a concept related to a class rather than a class instance, while a method is a local concept. They are attached to a class instance, and their life cycle is different from that of a class instance, unlike classes, internal variables in a method are revoked as the method is introduced. Therefore, local variables declared in a method body cannot be modified statically. Even if a method is declared as static, its internal variables cannot be declared as static. A static method modified by the static modifier can only access static variables modified by the static modifier in addition to the variables defined in the static modifier. To access the attributes of a non-static class, you must first instantiate a class instance and then reference the attributes of a non-static class through the class instance. However, a non-static method can access a static variable.

Note 2. The call methods for static and non-static methods are different. The call method for non-static methods is determined during the runtime, while the call to static methods occurs during the compilation period. A non-static method can call a static method, but a static method cannot call a non-static method directly, unless called through a class instance.

Note 3. A static method cannot be rewritten as a non-static method. It can only be rewritten as a static method, but can be reloaded as a non-static method. The meaning of rewriting is that there is always only one definition, the original meaning is completely replaced by the subsequent meaning, that is, the form cannot be changed. The meaning of heavy load means that the same thing has different meanings in different places.

Note 4: a static code block is not a method, but a static modifier followed by a method body (a group of statements in braces ). The static code block is mainly used for initialization. The code in this code block is executed only once, that is, before the constructor is executed, and only once. If the inherited parent class contains a static code block, execute the parent class first, but the static code block of the subclass must be prior to the constructor of the parent class. If a class contains multiple static code blocks, the running order depends on the sequence defined in the class.

Note 5. Non-static code blocks are not a method, but actually a method subject (a group of statements in braces ). When a class instance is created, the non-static code block is executed and runs after the parent class constructor and before the class constructor. If a class contains multiple non-static code blocks, the running sequence depends on the sequence defined in the class.

  The execution sequence of static and non-static code blocks is as follows:

1 public class Father {2 public Father () {3 System. out. println ("this is the construction method of the parent class! "); 4} 5 {6 System. out. println (" this is a non-static code block of the parent class! "); 7} 8 static {9 System. out. println (" this is the static code block of the parent class! "); 10} 11}
1 public class Son extends Father {2 public Son () {3 System. out. println ("this is the subclass construction method! "); 4} 5 {6 System. out. println (" this is a non-static code block of the subclass! "); 7} 8 static {9 System. out. println (" this is the static code block of the subclass! "); 10} 11}
1 public class Test {2     public static void main(String[] args) {3         new Son();4         new Son();5     }6 }

  Execution result:

1. This is the static code block of the parent class! 2. This is the static code block of the subclass! 3. This is a non-static code block of the parent class! 4. This is the construction method of the parent class! 5. This is a non-static code block of the subclass! 6. This is the subclass construction method! 7. This is a non-static code block of the parent class! 8. This is the construction method of the parent class! 9. This is a non-static code block of the subclass! 10. This is the subclass construction method!

Similarities: both are executed when the JVM loads the class and before the constructor executes it. Multiple classes can be defined. Generally, some static variables are assigned values in the code block.

Difference: static code blocks are executed before non-static code blocks. (Static code block> non-static code block> Constructor)The static code block is executed only once for the first time in new mode, but not once for every new time.. Non-static code blocks can be defined in common methods (but not very useful), while static code blocks cannot. When the JVM loads a class, these static code blocks are executed,If there are multiple static code blocks, JVM will execute them in sequence according to the order they appear in the class., Each code block is executed only once.

 

6. Differences between rewriting and overloading

1. Overloading)

(1) method Overloading is a means for classes to process different types of data in a unified manner. Multiple Functions with the same name exist at the same time and have different parameter numbers/types. Overload Overloading is a manifestation of polymorphism in a class.

(2) Java method overloading means that multiple methods can be created in the class. They have the same name, but have different parameters and different definitions. The number and type of parameters passed to a method are used to determine which method to use. This is polymorphism.

(3) During overload, the method name must be the same, but the parameter type or number are different. The return value type can be the same or different. Return types cannot be used as the criteria for distinguishing heavy-duty functions.

  Return types cannot be used as the criteria for distinguishing heavy-duty functions.
1 public class Test2 {2 public int test (int I, float f) {// compilation error 3 return I; 4} 5 public int test (int I, float f) {// compilation Error 6 return f; 7} 8}

  2. Overriding)

(1) The polymorphism between the parent class and the Child class, and the function of the parent class is redefined. If a subclass defines a method with the same name and parameter as its parent class, we say this method is overwritten ). In Java,Subclass can inherit the methods in the parent class without re-writing the same method. But sometimes subclass does not want to be originalInstead, we want to modify the method of the parent class. This requires method rewriting. Method RewritingMethod coverage.

(2) If the method in the subclass has the same method name, return type, and parameter table as a method in the parent class,The new method overwrites the original method. If you need the original method of the parent class, you can use the super keyword.
It references the parent class of the current class. (Rewriting does not mean destruction, but overwrite)

(3) The access modification permission of subclass functions cannot be less than that of the parent class;

    Summary: Reload and rewrite (overwrite ).
Overriding and Overloading are different manifestations of Java polymorphism. Overriding is a manifestation of the polymorphism between the parent class and the Child class, and Overloading is a manifestation of the polymorphism in a class. If a subclass defines a method with the same name and parameter as its parent class, we say this method is overwritten ). When a subclass object uses this method, the definition in the subclass is called. For it, the definition in the parent class is "blocked, in addition, if the method names and parameter types of the subclass are the same as those of the parent class, the return value type of the subclass must be the same as that of the parent class. If multiple methods with the same name are defined in a class, they may have different numbers of parameters or different parameter types, which are called Overloading ). The Overloaded method can change the type of the returned value. That is to say, the type of the returned value of the overload can be the same or different.

  3. Overload between subclass and parent class Method

1 // parent class 2 public class Father {3 public int eat (int I) {4 System. out. println ("I =" + I); 5 return I; 6} 7} 8 // subclass 9 public class Son extends Father {10 public float eat (float I) {11 System. out. println ("I =" + I); 12 return I; 13} 14} 15 // Test class 16 public class Test {17 public static void main (String [] args) {18 Son son = new Son (); 19 son. eat (10); 20 son. eat (float) 10.0); 21} 22} 23 // test result 24 I = 1025 I = 10.0

1. Override features

    1. the logo of the covered method must match the logo of the covered method to achieve the coverage effect;

    2. The returned value of the overwritten method must be the same as that of the overwritten method;

    3. The exception thrown by the overwriting method must be the same as that thrown by the overwriting method, or its subclass;

    4. The method is defined as final and cannot be overwritten.

    5. For inheritance, if the access permission of a method in the parent class is private, it cannot be overwritten in the subclass. If it is defined, it only defines a new method and does not overwrite the method. (Usually exists between the parent class and the Child class .)

2. Overload features

    1. You can only use different parameter styles when using overload. For example, different parameter types, different parameter numbers, and different parameter Order (of course, several parameter types in the same method must be different, such as fun (int, float ), but cannot be fun (int, int ));

    2. It cannot be overloaded by access permission, return type, or thrown exception;

3. The method exception type and quantity do not affect the heavy load;

4. Overload events usually occur between different methods in the same class, but can also occur in parent and child classes, as shown in the preceding program example.

  Its specific implementation mechanism: overload is heavy load, and overload is a parameter polymorphism mechanism, that is, code is implemented through different parameter types or numbers. It is a static binding mechanism (you already know which code segment is executed during compilation ). Override is overwrite. Overwriting is a dynamic binding polymorphism mechanism. That is, there are different implementation codes for elements with the same name (such as member functions) in the parent class and subclass. Which code is executed depends on the actual situation of the runtime.

 

 

 

 

 

 

 

 

 

 

 

 

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.