Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the comments in java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the notes in java". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the notes in java.

@ Override

The ability to override the implementation of methods or provide implementations for abstract methods is at the core of any object-oriented (OO) language. Because Java is an OO language with many common object-oriented abstraction mechanisms, any method in a non-final method or interface defined by a non-ultimate superclass (interface methods cannot be final) can be overridden by subclasses. Although the override method looks simple at first, many tiny bug may be introduced if it is not executed correctly. For example, overriding the Object#equals method with a single parameter of the override class type is a common error:

Public class Foo {public boolean equals (Foo foo) {/ / Check if the supplied object is equal to this object}}

Because all classes implicitly inherit from the Object class, the purpose of the Foo class is to override the Object#equals method, so Foo can be tested for equality with any other object in Java. Although our intentions are correct, our implementation is not. In fact, our implementation does not override the Object#equals method at all. Instead, we provide method overloading: instead of replacing the implementation of the equals method provided by the Object class, we provide a second method that specifically accepts Foo objects rather than Object objects. Our error can be illustrated by a simple implementation that returns true for all equality checks, but never calls the supplied object when it is considered an Object (an operation that Java will perform, for example, in Java Collections Framework, that is, JCF):

Public class Foo {public boolean equals (Foo foo) {return true;}} Object foo = new Foo (); Object identicalFoo = new Foo (); System.out.println (foo.equals (identicalFoo)); / / false

This is a very subtle but common error that can be caught by the compiler. Our intention is to override the Object#equals method, but because we specify a parameter of type Foo instead of Object, we actually provide an overloaded Object#equals method instead of overriding it. To catch this error, we introduce the @ Override annotation, which instructs the compiler to check whether the override is actually executed. If a valid override is not performed, an error is thrown. Therefore, we can update the Foo class as follows:

Public class Foo {@ Overridepublic boolean equals (Foo foo) {return true;}}

If we try to compile this class, we now receive the following error:

$javac Foo.javaFoo.java:3: error: method does not override or implement a method from a supertype@ override ^ 1 error

In essence, we have transformed the implicit assumption that we have overridden the method into explicit verification by the compiler. If our intention is incorrectly implemented, then the Java compiler will issue an error that does not allow our incorrectly implemented code to be compiled successfully. In general, if any of the following conditions are not met, the Java compiler will issue an error (referenced from the Override comment document) for methods that use @ Override annotations:

This method does override or implement methods declared in the superclass. The signature of this method is equivalent to the signature overlay of any public method (that is, the equals or hashCode method) declared in Object (override-equivalent).

Therefore, we can also use this annotation to ensure that subclass methods actually override non-final concrete or abstract methods in the superclass:

Public abstract class Foo {public int doSomething () {return 1;} public abstract int doSomethingElse ();} public class Bar extends Foo {@ Overridepublic int doSomething () {return 10;} @ Overridepublic int doSomethingElse () {return 20;}} Foo bar = new Bar (); System.out.println (bar.doSomething ()); / / 10System.out.println (bar.doSomethingElse ()); / / 20

The @ Override annotation is not limited to concrete or abstract methods in the superclass, but can also be used to ensure that the methods of the interface are also overridden:

Public interface Foo {public int doSomething ();} public class Bar implements Foo {@ Overridepublic int doSomething () {return 10;}} Foo bar = new Bar (); System.out.println (bar.doSomething ()); / / 10

In general, any method that overrides non-final class methods, abstract superclass methods, or interface methods can be annotated with @ Override. For more information about valid overrides, see the "Overriding and Hiding" documentation and Section 9.6.4.4 of "Java Language Specification (JLS)".

@ FunctionalInterface

With the introduction of lambda expressions in JDK 8, functional interfaces are becoming more and more popular in Java. These special types of interfaces can be replaced by lambda expressions, method references, or constructor references. According to the @ FunctionalInterface document, a functional interface is defined as follows:

A functional interface has only one abstract method. Because the default methods have an implementation, they are not abstract.

For example, the following interfaces are considered functional interfaces:

Public interface Foo {public int doSomething ();} public interface Bar {public int doSomething (); public default int doSomethingElse () {return 1;}}

Therefore, each of the following can be replaced with a lambda expression, as follows:

Public class FunctionalConsumer {public void consumeFoo (Foo foo) {System.out.println (foo.doSomething ());} public void consumeBar (Bar bar) {System.out.println (bar.doSomething ());}} FunctionalConsumer consumer = new FunctionalConsumer (); consumer.consumeFoo (()-> 10); / / 10consumer.consumeBar (()-> 20); / / 20

It is important to note that abstract classes, even if they contain only one abstract method, are not functional interfaces. For more information, see "Allow lambdas to implement abstract classes" written by Brian Goetz, the chief Java language architect. Similar to the @ Override annotation, the Java compiler provides the @ FunctionalInterface annotation to ensure that the interface is indeed a functional interface. For example, we can add this annotation to the interface created above:

@ FunctionalInterfacepublic interface Foo {public int doSomething ();} @ FunctionalInterfacepublic interface Bar {public int doSomething (); public default int doSomethingElse () {return 1;}}

If we mistakenly define an interface as a non-functional interface and annotate the wrong interface with @ FunctionalInterface, the Java compiler will issue an error. For example, we can define the following annotated non-functional interface:

@ FunctionalInterfacepublic interface Foo {public int doSomething (); public int doSomethingElse ();}

If we try to compile this interface, we get the following error:

$javac Foo.javaFoo.java:1: error: Unexpected @ FunctionalInterface annotation@ functional interaction ^ Foo is nota functional interfacemultiple non-overriding abstract methods found in interface Foo1 error

Using this annotation, we can ensure that we do not mistakenly create a non-functional interface that was intended to be used as a functional interface. It is important to note that even in the absence of the @ FunctionalInterface annotation, the interface can be used as a functional interface (which can be replaced by lambdas, method reference, and constructor reference), as we saw in the previous example. This is similar to the @ Override annotation, that is, a method can be overridden, even if it does not contain the @ Override annotation. In both cases, annotations are optional techniques that allow the compiler to perform the desired intent.

For more information about the @ FunctionalInterface annotation, see the @ FunctionalInterface documentation and section 4.6.4.9 of "JLS".

@ SuppressWarnings

Warnings are an important part of all compilers, providing feedback to developers-potentially dangerous behavior or errors that may occur in future compiler versions. For example, using a generic type in Java without its associated formal generic parameters (called primitive types) can cause warnings, just like using deprecated code (see the @ Deprecated section below). While these warnings are important, they may not always be applicable or even correct. For example, there may be warnings about unsafe type conversions, but we can guarantee that it is safe based on the context in which it is used.

To ignore specific warnings in some contexts, the @ SuppressWarnings annotation was introduced in JDK 5. This comment accepts one or more string parameters-- describing the warning name to ignore. Although the names of these warnings usually vary from compiler to compiler implementation, three warnings are standardized in the Java language (so they are common in all Java compiler implementations):

Unchecked: warning that type conversions are unchecked (the compiler cannot guarantee that type conversions are safe). Possible causes include access to members of the original type, narrow reference conversions or unsafe downward conversions, unchecked type conversions using generic parameters with variable parameters, and using invalid covariates to return type indeterminate parameter evaluations Unchecked method reference type conversions or unchecked lambda type dialogs). Deprecation: a warning indicating the use of deprecated methods, classes, types, etc.). Removal: a warning indicating the use of eventually obsolete methods, classes, types, etc.

To ignore a specific warning, you can add one or more names of the @ SuppressedWarning annotation and suppression warning (provided as an array of strings) to the context in which the warning occurs:

Public class Foo {public void doSomething (@ SuppressWarnings ("rawtypes") List myList) {/ / Do something with myList}}

The @ SuppressWarnings annotation can be used in any of the following situations:

Type domain method parameter constructor local variable module

In general, the @ SuppressWarnings annotation should be applied to the most direct warning range. For example, if a local variable in a method should ignore warnings, the @ SuppressWarnings annotation should be applied to the local variable, not to the method or class that contains the local variable:

Public class Foo {public void doSomething () {@ SuppressWarnings ("rawtypes") List myList = new ArrayList (); / / Do something with myList}}

@ SafeVarargs

Variable parameters are a useful technique in Java, but they can also cause serious problems when used with generic parameters. Because generics are nonspecific in Java, the actual (implementation) type of a variable with a generic type cannot be determined at run time. Because this judgment cannot be made, the variable may store references to the type that are not of its actual type, as shown in the following code snippet (excerpted from "Java Generics FAQs"):

List ln = new ArrayList (); ln.add (1); List ls = ln; / / unchecked warning String s = ls.get (0); / / ClassCastException

After ln is assigned to ls, there is a variable ls in the heap that has the type List, but stores a reference to a value that is actually of type List. This invalid reference is called heap pollution. Because this error is not determined until run time, it is displayed as a warning at compile time and ClassCastException appears at run time. This problem may be exacerbated when generic parameters are combined with variable parameters:

Public class Foo {public void doSomething (T... Args) {/ /.}}

In this case, the Java compiler creates an array inside the calling site to store a variable number of parameters, but the type of T is not implemented, so it is lost at run time. In essence, the parameters to doSomething are actually of type Object []. If you rely on the runtime type of T, this can cause serious problems, as shown in the following code snippet:

Public class Foo {public void doSomething (T... Args) {Object [] objects = args;String string = (String) objects [0];}} Foo foo = new Foo (); foo.doSomething (1,2)

If this code snippet is executed, it will result in a ClassCastException because the first Number parameter passed at the calling site cannot be converted to String (similar to the ClassCastException thrown in the stand-alone heap contamination example). In general, it is possible that the compiler does not have enough information to correctly determine the exact type of generic variable parameters, which can lead to heap contamination, which can be propagated by allowing internal variable parameter arrays to escape from methods, such as the following example from pp.147, version 3 of Effective Java:

Public static T [] toArray (T... Args) {return args;}

In some cases, we know that the method is actually type-safe and does not cause heap pollution. If this decision can be made with assurance, we can annotate the method with the @ SafeVarargs annotation, thereby suppressing warnings related to possible heap contamination. However, this raises the question: when will generic variable parameter methods be considered type-safe? Josh Bloch provides a complete solution based on page 147 of the third edition of "Effective Java"-based interaction between methods and internally created arrays to store their variable parameters:

If the method does not store anything into the array (which overrides parameters) and does not allow the escape of references to the array (which allows untrusted code to access the array), then it is safe. In other words, if the variable parameter array is only used to pass a variable number of parameters from the caller to the method-- after all, that's the purpose of the variable parameters-- then the method is safe.

So, if we create the following method (from pp.149 above), we can annotate our method reasonably with the @ SafeVarags annotation:

@ SafeVarargsstatic List flatten (List

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report