Java syntax: Difference between revisions

Content deleted Content added
Dormantor (talk | contribs)
No edit summary
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags
Line 184:
[[Variable (programming)|Variables]] are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.
 
<sourcesyntaxhighlight lang="java">
int count; //Declaring an uninitialized variable called 'count', of type 'int'
count = 35; //Initializing the variable
int count = 35; //Declaring and initializing the variable at the same time
</syntaxhighlight>
</source>
 
Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.
<sourcesyntaxhighlight lang="java">
int a, b; //Declaring multiple variables of the same type
int a = 2, b = 3; //Declaring and initializing multiple variables of the same type
</syntaxhighlight>
</source>
 
===Code blocks===
Line 221:
Traditional comments, also known as block comments, start with <code>/*</code> and end with <code>*/</code>, they may span across multiple lines. This type of comment was derived from C and C++.
 
<sourcesyntaxhighlight lang="java">
/* This is a multi-line comment.
It may occupy more than one line. */
</syntaxhighlight>
</source>
 
End-of-line comments start with <code>//</code> and extend to the end of the current line. This comment type is also present in C++ and in modern C.
<sourcesyntaxhighlight lang="java">
// This is an end-of-line comment
</syntaxhighlight>
</source>
 
Documentation comments in the source files are processed by the [[Javadoc]] tool to generate documentation. This type of comment is identical to traditional comments, except it starts with <code>/**</code> and follows conventions defined by the Javadoc tool. Technically, these comments are a special kind of traditional comment and they are not specifically defined in the language specification.
<sourcesyntaxhighlight lang="java">
/**
* This is a documentation comment.
Line 238:
* @author John Doe
*/
</syntaxhighlight>
</source>
 
===Universal types===
Line 253:
===<code>main</code> method===
Every Java application must have an entry point. This is true of both graphical interface applications and console applications. The entry point is the <code>main</code> method. There can be more than one class with a <code>main</code> method, but the main class is always defined externally (for example, in a [[manifest file]]). The method must be <code>static</code> and is passed command-line arguments as an array of strings. Unlike [[C++]] or [[C Sharp (programming language)|C#]], it never returns a value and must return <code>void</code>.
<sourcesyntaxhighlight lang=Java>
public static void main(String[] args) {
}
</syntaxhighlight>
</source>
 
===Packages===
Line 263:
A package is declared at the start of the file with the <code>package</code> declaration:
 
<sourcesyntaxhighlight lang=Java>
package myapplication.mylibrary;
 
public class MyClass {
}
</syntaxhighlight>
</source>
 
Classes with the <code>public</code> modifier must be placed in the files with the same name and <tt>java</tt> extension and put into nested folders corresponding to the package name. The above class <code>myapplication.mylibrary.MyClass</code> will have the following path: <code>myapplication/mylibrary/MyClass.java</code>.
Line 278:
A type import declaration allows a named type to be referred to by a simple name rather than the full name that includes the package. Import declarations can be ''single type import declarations'' or ''import-on-demand declarations''. Import declarations must be placed at the top of a code file after the package declaration.
 
<sourcesyntaxhighlight lang="java">
package myPackage;
 
Line 292:
}
}
</syntaxhighlight>
</source>
 
Import-on-demand declarations are mentioned in the code. A "type import" imports all the types of the package. A "static import" imports members of the package.
 
<sourcesyntaxhighlight lang="java">
import java.util.*; /*This form of importing classes makes all classes
in package java.util available by name, could be used instead of the
Line 303:
are no classes directly in package java. All of them are in packages
within package java. This does not import all available classes.*/
</syntaxhighlight>
</source>
 
====Static import declaration====
Line 309:
This type of declaration has been available since [[J2SE 5.0]]. [[static imports|Static import]] declarations allow access to static members defined in another class, interface, annotation, or enum; without specifying the class name:
 
<sourcesyntaxhighlight lang="java">
import static java.lang.System.out; //'out' is a static field in java.lang.System
 
Line 321:
}
}
</syntaxhighlight>
</source>
 
Import-on-demand declarations allow to import all the fields of the type:
 
<sourcesyntaxhighlight lang="java">
import static java.lang.System.*;
/* This form of declaration makes all
fields in the java.lang.System class available by name, and may be used instead
of the import declaration in the previous example. */
</syntaxhighlight>
</source>
 
Enum constants may also be used with static import. For example, this enum is in the package called <code>screen</code>:
 
<sourcesyntaxhighlight lang="java">
public enum ColorName {
RED, BLUE, GREEN
};
</syntaxhighlight>
</source>
 
It is possible to use static import declarations in another class to retrieve the enum constants:
 
<sourcesyntaxhighlight lang="java">
import screen.ColorName;
import static screen.ColorName.*;
Line 358:
}
}
</syntaxhighlight>
</source>
 
==Operators==
Line 505:
 
Also, note that the [[?:]] operator can be used in place of simple if statement, for example
<sourcesyntaxhighlight lang="java">
int a = 1;
int b = 2;
int minVal = (a < b) ? a : b;
</syntaxhighlight>
</source>
 
====<code>switch</code> statement====
Line 539:
In the <code>while</code> loop, the test is done before each iteration.
 
<sourcesyntaxhighlight lang="java">
while (i < 10) {
doSomething();
}
</syntaxhighlight>
</source>
 
====<code>do ... while</code> loop====
In the <code>do ... while</code> loop, the test is done after each iteration. Consequently, the code is always executed at least once.
 
<sourcesyntaxhighlight lang="java">
// doSomething() is called at least once
do {
doSomething();
} while (i < 10);
</syntaxhighlight>
</source>
 
====<code>for</code> loop====
<code>for</code> loops in Java include an initializer, a condition and a counter expression. It is possible to include several expressions of the same kind using comma as delimiter (except in the condition). However, unlike C, the comma is just a delimiter and not an operator.
 
<sourcesyntaxhighlight lang="java">
for (int i = 0; i < 10; i++) {
doSomething();
Line 567:
doSomething();
}
</syntaxhighlight>
</source>
 
Like C, all three expressions are optional. The following loop is infinite:
<sourcesyntaxhighlight lang="java">
for (;;) {
doSomething();
}
</syntaxhighlight>
</source>
 
====Enhanced <code>for</code> loop====
Line 580:
[[enhanced for loop|Enhanced <code>for</code> loop]]s have been available since [[J2SE 5.0]]. This type of loop uses built-in iterators over arrays and collections to return each item in the given collection. Every element is returned and reachable in the context of the code block. When the block is executed, the next item is returned until there are no items remaining. Unlike [[C Sharp (programming language)|C#]], this kind of loop does not involve a special keyword, but instead uses a different notation style.
 
<sourcesyntaxhighlight lang="java">
for (int i : intArray) {
doSomething(i);
}
</syntaxhighlight>
</source>
 
===Jump statements===
Line 591:
Labels are given points in code used by <code>break</code> and <code>continue</code> statements. Note that the Java <code>goto</code> keyword cannot be used to jump to specific points in the code.
 
<sourcesyntaxhighlight lang="java">
start:
someMethod();
</syntaxhighlight>
</source>
 
====<code>break</code> statement====
The <code>break</code> statement breaks out of the closest loop or <code>switch</code> statement. Execution continues in the statement after the terminated statement, if any.
 
<sourcesyntaxhighlight lang="java">
for (int i = 0; i < 10; i++) {
while (true) {
Line 606:
// Will break to this point
}
</syntaxhighlight>
</source>
 
It is possible to break out of the outer loop using labels:
 
<sourcesyntaxhighlight lang="java">
outer:
for (int i = 0; i < 10; i++) {
Line 618:
}
// Will break to this point
</syntaxhighlight>
</source>
 
====<code>continue</code> statement====
The <code>continue</code> statement discontinues the current iteration of the current control statement and begins the next iteration. The following <code>while</code> loop in the code below reads characters by calling <code>getChar()</code>, skipping the statements in the body of the loop if the characters are spaces:
 
<sourcesyntaxhighlight lang="java">
int ch;
while (ch == getChar()) {
Line 633:
doSomething();
}
</syntaxhighlight>
</source>
 
Labels can be specified in <code>continue</code> statements and <code>break</code> statements:
 
<sourcesyntaxhighlight lang="java">
outer:
for (String str : stringsArr) {
Line 650:
}
}
</syntaxhighlight>
</source>
 
====<code>return</code> statement====
The <code>return</code> statement is used to end method execution and to return a value. A value returned by the method is written after the <code>return</code> keyword. If the method returns anything but <code>void</code>, it must use the <code>return</code> statement to return some value.
 
<sourcesyntaxhighlight lang="java">
void doSomething(boolean streamClosed) {
// If streamClosed is true, execution is stopped
Line 668:
return result;
}
</syntaxhighlight>
</source>
 
<code>return</code> statement ends execution immediately, except for one case: if the statement is encountered within a <code>try</code> block and it is complemented by a <code>finally</code>, control is passed to the <code>finally</code> block.
 
<sourcesyntaxhighlight lang="java">
void doSomething(boolean streamClosed) {
try {
Line 685:
}
}
</syntaxhighlight>
</source>
 
===Exception handling statements===
Line 741:
The <code>throw</code> statement is used to throw an exception and end the execution of the block or method. The thrown exception instance is written after the <code>throw</code> statement.
 
<sourcesyntaxhighlight lang="java">
void methodThrowingExceptions(Object obj) {
if (obj == null) {
Line 750:
doSomethingWithObject(obj);
}
</syntaxhighlight>
</source>
 
===Thread concurrency control===
Line 768:
<code>assert</code> statements have been available since [[J2SE 1.4]]. These types of statements are used to make [[assertion (computing)|assertion]]s in the source code, which can be turned on and off during execution for specific classes or packages. To declare an assertion the <code>assert</code> keyword is used followed by a conditional expression. If it evaluates to <code>false</code> when the statement is executed, an exception is thrown. This statement can include a colon followed by another expression, which will act as the exception's detail message.
 
<sourcesyntaxhighlight lang="java">
// If n equals 0, AssertionError is thrown
assert n != 0;
Line 774:
with the message after the colon */
assert n != 0 : "n was equal to zero";
</syntaxhighlight>
</source>
 
==Primitive types==
Line 853:
 
Example:
<sourcesyntaxhighlight lang="java">
int foo = 42; // Primitive type
Integer bar = foo; /* foo is boxed to bar, bar is of Integer type,
which serves as a wrapper for int */
int foo2 = bar; // Unboxed back to primitive type
</syntaxhighlight>
</source>
 
==Reference types==
Line 868:
Arrays in Java are created at runtime, just like class instances. Array length is defined at creation and cannot be changed.
 
<sourcesyntaxhighlight lang="java">
int[] numbers = new int[5];
numbers[0] = 2;
numbers[1] = 5;
int x = numbers[0];
</syntaxhighlight>
</source>
 
====Initializers====
 
<sourcesyntaxhighlight lang="java">
// Long syntax
int[] numbers = new int[] {20, 1, 42, 15, 34};
// Short syntax
int[] numbers2 = {20, 1, 42, 15, 34};
</syntaxhighlight>
</source>
 
====Multi-dimensional arrays====
In Java, multi-dimensional arrays are represented as arrays of arrays. Technically, they are represented by arrays of references to other arrays.
 
<sourcesyntaxhighlight lang="java">
int[][] numbers = new int[3][3];
numbers[1][2] = 2;
 
int[][] numbers2 = {{2, 3, 2}, {1, 2, 6}, {2, 4, 5}};
</syntaxhighlight>
</source>
 
Due to the nature of the multi-dimensional arrays, sub-arrays can vary in length, so multi-dimensional arrays are not bound to be rectangular unlike C:
<sourcesyntaxhighlight lang=Java>
int[][] numbers = new int[2][]; //Initialization of the first dimension only
 
numbers[0] = new int[3];
numbers[1] = new int[2];
</syntaxhighlight>
</source>
 
===Classes===
Line 909:
|-
! Top-level class
|<sourcesyntaxhighlight lang="java">
class Foo {
// Class members
}
</syntaxhighlight>
</source>
|-
!Inner class
|<sourcesyntaxhighlight lang="java">
class Foo { // Top-level class
class Bar { // Inner class
}
}
</syntaxhighlight>
</source>
|-
!Nested class
|<sourcesyntaxhighlight lang="java">
class Foo { // Top-level class
static class Bar { // Nested class
}
}
</syntaxhighlight>
</source>
|-
! Local class
|<sourcesyntaxhighlight lang="java">
class Foo {
void bar() {
Line 939:
}
}
</syntaxhighlight>
</source>
|-
! Anonymous class
|<sourcesyntaxhighlight lang="java">
class Foo {
void bar() {
Line 949:
}
}
</syntaxhighlight>
</source>
|}
 
Line 955:
Non-static members of a class define the types of the instance variables and methods, which are related to the objects created from that class. To create these objects, the class must be instantiated by using the <code>new</code> operator and calling the class constructor.
 
<sourcesyntaxhighlight lang="java">
Foo foo = new Foo();
</syntaxhighlight>
</source>
 
====Accessing members====
Line 965:
Instance members can be accessed through the name of a variable.
 
<sourcesyntaxhighlight lang="java">
String foo = "Hello";
String bar = foo.toUpperCase();
</syntaxhighlight>
</source>
 
'''Accessing a static class member'''<br/>
Static members are accessed by using the name of the class or any other type. This does not require the creation of a class instance. Static members are declared using the <code>static</code> modifier.
 
<sourcesyntaxhighlight lang="java">
public class Foo {
public static void doSomething() {
Line 981:
// Calling the static method
Foo.doSomething();
</syntaxhighlight>
</source>
 
====Modifiers====
Line 994:
The ''access modifiers'', or ''inheritance modifiers'', set the accessibility of classes, methods, and other members. Members marked as <code>public</code> can be reached from anywhere. If a class or its member does not have any modifiers, default access is assumed.
 
<sourcesyntaxhighlight lang="java">
public class Foo {
int go() {
Line 1,003:
}
}
</syntaxhighlight>
</source>
 
The following table shows whether code within a class has access to the class or method depending on the accessing class ___location and the modifier for the accessed class or class member:
Line 1,045:
A [[Constructor (computer science)|constructor]] is a special method called when an object is initialized. Its purpose is to initialize the members of the object. The main differences between constructors and ordinary methods are that constructors are called only when an instance of the class is created and never return anything. Constructors are declared as common methods, but they are named after the class and no return type is specified:
 
<sourcesyntaxhighlight lang="java">
class Foo {
String str;
Line 1,058:
}
}
</syntaxhighlight>
</source>
 
Initializers are blocks of code that are executed when a class or an instance of a class is created. There are two kinds of initializers, ''static initializers'' and ''instance initializers''.
Line 1,064:
Static initializers initialize static fields when the class is created. They are declared using the <code>static</code> keyword:
 
<sourcesyntaxhighlight lang="java">
class Foo {
static {
Line 1,070:
}
}
</syntaxhighlight>
</source>
 
A class is created only once. Therefore, static initializers are not called more than once. On the contrary, instance initializers are automatically called before the call to a constructor every time an instance of the class is created. Unlike constructors instance initializers cannot take any arguments and generally they cannot throw any [[Exception handling#Checked exceptions|checked exceptions]] (except in several special cases). Instance initializers are declared in a block without any keywords:
 
<sourcesyntaxhighlight lang="java">
class Foo {
{
Line 1,080:
}
}
</syntaxhighlight>
</source>
 
Since Java has a garbage collection mechanism, there are no [[Destructor (computer science)|destructors]]. However, every object has a <code>finalize()</code> method called prior to garbage collection, which can be overridden to implement finalization.
Line 1,087:
All the statements in Java must reside within methods. Methods are similar to functions except they belong to classes. A method has a return value, a name and usually some parameters initialized when it is called with some arguments. Similar to C++, methods returning nothing have return type declared as <code>void</code>. Unlike in C++, methods in Java are not allowed to have default argument values and methods are usually overloaded instead.
 
<sourcesyntaxhighlight lang="java">
class Foo {
int bar(int a, int b) {
Line 1,098:
}
}
</syntaxhighlight>
</source>
 
A method is called using <code>.</code> notation on an object, or in the case of a static method, also on the name of a class.
 
<sourcesyntaxhighlight lang="java">
Foo foo = new Foo();
int result = foo.bar(7, 2); // Non-static method is called on foo
 
int finalResult = Math.abs(result); // Static method call
</syntaxhighlight>
</source>
 
The <code>throws</code> keyword indicates that a method throws an exception. All checked exceptions must be listed in a comma-separated list.
<sourcesyntaxhighlight lang="java">
void openStream() throws IOException, myException { // Indicates that IOException may be thrown
}
</syntaxhighlight>
</source>
 
=====Lambda expressions=====
<sourcesyntaxhighlight lang="text">
(variables) -> {body}
variable -> body_with_one_statement
(type variable) -> {}
</syntaxhighlight>
</source>
 
=====Modifiers=====
Line 1,134:
This language feature was introduced in [[J2SE 5.0]]. The last argument of the method may be declared as a variable arity parameter, in which case the method becomes a variable arity method (as opposed to fixed arity methods) or simply [[variadic function|varargs]] method. This allows one to pass a variable number of values, of the declared type, to the method as parameters - including no parameters. These values will be available inside the method as an array.
 
<sourcesyntaxhighlight lang="java">
void printReport(String header, int... numbers) { //numbers represents varargs
System.out.println(header);
Line 1,144:
// Calling varargs method
printReport("Report data", 74, 83, 25, 96);
</syntaxhighlight>
</source>
 
====Fields====
Fields, or class variables, can be declared inside the class body to store data.
 
<sourcesyntaxhighlight lang="java">
class Foo {
double bar;
}
</syntaxhighlight>
</source>
 
Fields can be initialized directly when declared.
 
<sourcesyntaxhighlight lang="java">
class Foo {
double bar = 2.3;
}
</syntaxhighlight>
</source>
 
=====Modifiers=====
Line 1,172:
Classes in Java can only [[Inheritance (computer science)|inherit]] from ''one'' class. A class can be derived from any class that is not marked as <code>final</code>. Inheritance is declared using the <code>extends</code> keyword. A class can reference itself using the <code>this</code> keyword and its direct superclass using the <code>super</code> keyword.
 
<sourcesyntaxhighlight lang="java">
class Foo {
 
Line 1,180:
 
}
</syntaxhighlight>
</source>
 
If a class does not specify its superclass, it implicitly inherits from <code>java.lang.Object</code> class. Thus all classes in Java are subclasses of <code>Object</code> class.
Line 1,186:
If the superclass does not have a constructor without parameters the subclass must specify in its constructors what constructor of the superclass to use. For example:
 
<sourcesyntaxhighlight lang="java">
class Foo {
public Foo(int n) {
Line 1,203:
}
}
</syntaxhighlight>
</source>
 
=====Overriding methods=====
Unlike C++, all non-<code>final</code> methods in Java are [[Virtual function|virtual]] and can be overridden by the inheriting classes.
 
<sourcesyntaxhighlight lang="java">
class Operation {
public int doSomething() {
Line 1,221:
}
}
</syntaxhighlight>
</source>
 
=====Abstract classes=====
Line 1,234:
* A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class.
 
<sourcesyntaxhighlight lang="java">
package org.dwwwp.test;
 
Line 1,260:
}
}
</syntaxhighlight>
</source>
<sourcesyntaxhighlight lang="java">
package org.dwwwp.test;
 
Line 1,287:
}
}
</syntaxhighlight>
</source>
 
Output:
<sourcesyntaxhighlight lang="text">
org.dwwwp.test.AbstractClass: static block runtime
org.dwwwp.test.CustomClass: static block runtime
Line 1,298:
org.dwwwp.test.CustomClass: constructor runtime
hello from org.dwwwp.test.AbstractClass
</syntaxhighlight>
</source>
 
====Enumerations====
This language feature was introduced in [[J2SE 5.0]]. Technically enumerations are a kind of class containing enum constants in its body. Each enum constant defines an instance of the enum type. Enumeration classes cannot be instantiated anywhere except in the enumeration class itself.
 
<sourcesyntaxhighlight lang="java">
enum Season {
WINTER, SPRING, SUMMER, AUTUMN
}
</syntaxhighlight>
</source>
 
Enum constants are allowed to have constructors, which are called when the class is loaded:
 
<sourcesyntaxhighlight lang="java">
public enum Season {
WINTER("Cold"), SPRING("Warmer"), SUMMER("Hot"), AUTUMN("Cooler");
Line 1,325:
}
}
</syntaxhighlight>
</source>
 
Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class:
 
<sourcesyntaxhighlight lang="java">
public enum Season {
WINTER {
Line 1,344:
};
}
</syntaxhighlight>
</source>
 
===Interfaces===
Interfaces are data structures that contain member definitions and not actual implementation. They are useful to define a contract between members in different types that have different implementations. Every interface is implicitly abstract. The only modifier allowed to use with interfaces apart from access modifiers is <code>strictfp</code>, which has the same effect as for classes.
 
<sourcesyntaxhighlight lang="java">
interface ActionListener {
int ACTION_ADD = 0;
Line 1,356:
void actionSelected(int action);
}
</syntaxhighlight>
</source>
 
====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. Class implementing an interface must override all its methods, otherwise it must be declared as abstract.
 
<sourcesyntaxhighlight lang="java">
interface RequestListener {
int requestReceived();
Line 1,379:
listener.requestReceived(); /*...and thus is known to implement
requestReceived() method*/
</syntaxhighlight>
</source>
 
====Inheritance====
Line 1,385:
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.
 
<sourcesyntaxhighlight lang="java">
/* Class implementing this interface must implement methods of both
ActionListener and RequestListener */
Line 1,391:
}
</syntaxhighlight>
</source>
 
====Annotations====
Line 1,399:
=====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.
<sourcesyntaxhighlight lang="java">
@interface BlockingOperations {
}
</syntaxhighlight>
</source>
 
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:
 
<sourcesyntaxhighlight lang="java">
@interface BlockingOperations {
boolean fileSystemOperations();
boolean networkOperations() default false;
}
</syntaxhighlight>
</source>
 
=====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.
 
<sourcesyntaxhighlight lang="java">
@BlockingOperations(/*mandatory*/ fileSystemOperations,
/*optional*/ networkOperations = true)
void openOutputStream() { //Annotated method
}
</syntaxhighlight>
</source>
 
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:
<sourcesyntaxhighlight lang="java">
@Unused // Shorthand for @Unused()
void travelToJupiter() {
}
</syntaxhighlight>
</source>
 
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:
 
<sourcesyntaxhighlight lang="java">
/* Equivalent for @BlockingOperations(fileSystemOperations = true).
networkOperations has a default value and
Line 1,440:
void openOutputStream() {
}
</syntaxhighlight>
</source>
 
==Generics==
Line 1,452:
It is possible to limit a type variable to a subtype of some specific class or declare an interface that must be implemented by the type. In this case the type variable is appended by the <code>extends</code> keyword followed by a name of the class or the interface. If the variable is constrained by both class and interface or if there are several interfaces, the class name is written first, followed by interface names with <code>& </code> sign used as the delimiter.
 
<sourcesyntaxhighlight lang="java">
/* This class has two type variables, T and V. T must be
a subtype of ArrayList and implement Formattable interface */
Line 1,461:
}
}
</syntaxhighlight>
</source>
 
When a variable of a parameterized type is declared or an instance is created, its type is written exactly in the same format as in the class header, except the actual type is written in the place of the type variable declaration.
Line 1,495:
Usage of generics may be limited to some particular methods, this concept applies to constructors as well. To declare a parameterized method, type variables are written before the return type of the method in the same format as for the generic classes. In the case of constructor, type variables are declared before the constructor name.
 
<sourcesyntaxhighlight lang="java">
class Mapper {
// The class itself is not generic, the constructor is
Line 1,512:
return false;
}
</syntaxhighlight>
</source>
 
===Generic interfaces===
Interfaces can be parameterized in the similar manner as the classes.
 
<sourcesyntaxhighlight lang="java">
interface Expandable<T extends Number> {
void addItem(T item);
Line 1,533:
}
}
</syntaxhighlight>
</source>
 
== See also ==