Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Java syntax
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Interfaces=== [[Interface (Java)|Interfaces]] are types which contain no fields and usually define a number of methods without an actual implementation. They are useful to define a contract with any number of different implementations. Every interface is implicitly abstract. Interface methods are allowed to have a subset of access modifiers depending on the language version, <code>strictfp</code>, which has the same effect as for classes, and also <code>static</code> since Java SE 8. <syntaxhighlight lang="java"> interface ActionListener { int ACTION_ADD = 0; int ACTION_REMOVE = 1; void actionSelected(int action); } </syntaxhighlight> ====Implementing an interface==== An interface is implemented by a class using the <code>implements</code> keyword. It is allowed to implement more than one interface, in which case they are written after <code>implements</code> keyword in a comma-separated list. A class implementing an interface must override all its methods, otherwise it must be declared as abstract. <syntaxhighlight lang="java"> interface RequestListener { int requestReceived(); } class ActionHandler implements ActionListener, RequestListener { public void actionSelected(int action) { } public int requestReceived() { } } //Calling method defined by interface RequestListener listener = new ActionHandler(); /*ActionHandler can be represented as RequestListener...*/ listener.requestReceived(); /*...and thus is known to implement requestReceived() method*/ </syntaxhighlight> ====Functional interfaces and lambda expressions==== These features were introduced with the release of Java SE 8. An interface automatically becomes a functional interface if it defines only one method. In this case an implementation can be represented as a lambda expression instead of implementing it in a new class, thus greatly simplifying writing code in the [[functional programming|functional style]]. Functional interfaces can optionally be annotated with the <code>[[@FunctionalInterface]]</code> annotation, which will tell the compiler to check whether the interface actually conforms to a definition of a functional interface. <syntaxhighlight lang="java"> // A functional interface @FunctionalInterface interface Calculation { int calculate(int someNumber, int someOtherNumber); } // A method which accepts this interface as a parameter int runCalculation(Calculation calculation) { return calculation.calculate(1, 2); } // Using a lambda to call the method runCalculation((number, otherNumber) -> number + otherNumber); // Equivalent code which uses an anonymous class instead runCalculation(new Calculation() { @Override public int calculate(int someNumber, int someOtherNumber) { return someNumber + someOtherNumber; } }) </syntaxhighlight> Lambda's parameters types do not have to be fully specified and can be inferred from the interface it implements. Lambda's body can be written without a body block and a <code>return</code> statement if it is only an expression. Also, for those interfaces which only have a single parameter in the method, round brackets can be omitted.<ref>{{Cite web|title=Lambda Expressions (The Javaβ’ Tutorials > Learning the Java Language > Classes and Objects)|url=https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html|access-date=August 8, 2021|website=docs.oracle.com|archive-date=June 16, 2020|archive-url=https://web.archive.org/web/20200616055353/https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html|url-status=live}}</ref> <syntaxhighlight lang="java"> // Same call as above, but with fully specified types and a body block runCalculation((int number, int otherNumber) -> { return number + otherNumber; }); // A functional interface with a method which has only a single parameter interface StringExtender { String extendString(String input); } // Initializing a variable of this type by using a lambda StringExtender extender = input -> input + " Extended"; </syntaxhighlight> ====Method references==== It is not necessary to use lambdas when there already is a named method compatible with the interface. This method can be passed instead of a lambda using a method reference. There are several types of method references: {| class="wikitable" |- ! Reference type !! Example !! Equivalent lambda |- | Static || <code>Integer::sum</code> || <code>(number, otherNumber) -> number + otherNumber</code> |- | Bound || <code>"LongString"::substring</code> || <code>index -> "LongString".substring(index)</code> |- | Unbound || <code>String::isEmpty</code> || <code>string -> string.isEmpty()</code> |- | Class constructor || <code>ArrayList<String>::new</code> || <code>capacity -> new ArrayList<String>(capacity)</code> |- | Array constructor || <code>String[]::new</code> || <code>size -> new String[size]</code> |} The code above which calls <code>runCalculation</code> could be replaced with the following using the method references: <syntaxhighlight lang="java> runCalculation(Integer::sum); </syntaxhighlight> ====Inheritance==== Interfaces can inherit from other interfaces just like classes. Unlike classes it is allowed to inherit from multiple interfaces. However, it is possible that several interfaces have a field with the same name, in which case it becomes a single ambiguous member, which cannot be accessed. <syntaxhighlight lang="java"> /* Class implementing this interface must implement methods of both ActionListener and RequestListener */ interface EventListener extends ActionListener, RequestListener { } </syntaxhighlight> ====Default methods==== Java SE 8 introduced default methods to interfaces which allows developers to add new methods to existing interfaces without breaking compatibility with the classes already implementing the interface. Unlike regular interface methods, default methods have a body which will get called in the case if the implementing class does not override it. <syntaxhighlight lang="java"> interface StringManipulator { String extendString(String input); // A method which is optional to implement default String shortenString(String input) { return input.substring(1); } } // This is a valid class despite not implementing all the methods class PartialStringManipulator implements StringManipulator { @Override public String extendString(String input) { return input + " Extended"; } } </syntaxhighlight> ====Static methods==== {{Main|Method (computer programming)#Static methods}} Static methods is another language feature introduced in Java SE 8. They behave in exactly the same way as in the classes. <syntaxhighlight lang="java"> interface StringUtils { static String shortenByOneSymbol(String input) { return input.substring(1); } } StringUtils.shortenByOneSymbol("Test"); </syntaxhighlight> ====Private methods==== Private methods were added in the Java 9 release. An interface can have a method with a body marked as private, in which case it will not be visible to inheriting classes. It can be called from default methods for the purposes of code reuse. <syntaxhighlight lang="java"> interface Logger { default void logError() { log(Level.ERROR); } default void logInfo() { log(Level.INFO); } private void log(Level level) { SystemLogger.log(level.id); } } </syntaxhighlight> ====Annotations==== {{Main|Java annotation}} Annotations in Java are a way to embed [[metadata]] into code. This language feature was introduced in [[J2SE 5.0]]. =====Annotation types===== Java has a set of predefined annotation types, but it is allowed to define new ones. An annotation type declaration is a special type of an interface declaration. They are declared in the same way as the interfaces, except the <code>interface</code> keyword is preceded by the <code>@</code> sign. All annotations are implicitly extended from <code>java.lang.annotation.Annotation</code> and cannot be extended from anything else. <syntaxhighlight lang="java"> @interface BlockingOperations { } </syntaxhighlight> Annotations may have the same declarations in the body as the common interfaces, in addition they are allowed to include enums and annotations. The main difference is that abstract method declarations must not have any parameters or throw any exceptions. Also they may have a default value, which is declared using the <code>default</code> keyword after the method name: <syntaxhighlight lang="java"> @interface BlockingOperations { boolean fileSystemOperations(); boolean networkOperations() default false; } </syntaxhighlight> =====Usage of annotations===== Annotations may be used in any kind of declaration, whether it is package, class (including enums), interface (including annotations), field, method, parameter, constructor, or local variable. Also they can be used with enum constants. Annotations are declared using the <code>@</code> sign preceding annotation type name, after which element-value pairs are written inside brackets. All elements with no default value must be assigned a value. <syntaxhighlight lang="java"> @BlockingOperations(/*mandatory*/ fileSystemOperations, /*optional*/ networkOperations = true) void openOutputStream() { //Annotated method } </syntaxhighlight> Besides the generic form, there are two other forms to declare an annotation, which are shorthands. ''Marker annotation'' is a short form, it is used when no values are assigned to elements: <syntaxhighlight lang="java"> @Unused // Shorthand for @Unused() void travelToJupiter() { } </syntaxhighlight> The other short form is called ''single element annotation''. It is used with annotations types containing only one element or in the case when multiple elements are present, but only one elements lacks a default value. In single element annotation form the element name is omitted and only value is written instead: <syntaxhighlight lang="java"> /* Equivalent for @BlockingOperations(fileSystemOperations = true). networkOperations has a default value and does not have to be assigned a value */ @BlockingOperations(true) void openOutputStream() { } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)