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!
===Classes=== [[Class (computer programming)|Classes]] are fundamentals of an object-oriented language such as Java. They contain members that store and manipulate data. Classes are divided into ''top-level'' and ''nested''. Nested classes are classes placed inside another class that may access the private members of the enclosing class. Nested classes include ''member classes'' (which may be defined with the ''static'' modifier for simple nesting or without it for inner classes), ''local classes'' and ''anonymous classes''. ====Declaration==== {| class="wikitable" |- ! Top-level class |<syntaxhighlight lang="java"> class Foo { // Class members } </syntaxhighlight> |- !Inner class |<syntaxhighlight lang="java"> class Foo { // Top-level class class Bar { // Inner class } } </syntaxhighlight> |- !Nested class |<syntaxhighlight lang="java"> class Foo { // Top-level class static class Bar { // Nested class } } </syntaxhighlight> |- ! Local class |<syntaxhighlight lang="java"> class Foo { void bar() { class Foobar {// Local class within a method } } } </syntaxhighlight> |- ! Anonymous class |<syntaxhighlight lang="java"> class Foo { void bar() { new Object() {// Creation of a new anonymous class extending Object }; } } </syntaxhighlight> |} ====Instantiation==== Non-static members of a class define the types of the [[instance variable]]s 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. <syntaxhighlight lang="java"> Foo foo = new Foo(); </syntaxhighlight> ====Accessing members==== Members of both instances and static classes are accessed with the <code>.</code> (dot) operator. '''Accessing an instance member'''<br/> Instance members can be accessed through the name of a variable. <syntaxhighlight lang="java"> String foo = "Hello"; String bar = foo.toUpperCase(); </syntaxhighlight> '''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. <syntaxhighlight lang="java"> public class Foo { public static void doSomething() { } } // Calling the static method Foo.doSomething(); </syntaxhighlight> ====Modifiers==== Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers. * '''<code>abstract</code>''' - Specifies that a class only serves as a base class and cannot be instantiated. * '''<code>static</code>''' - Used only for member classes, specifies that the member class does not belong to a specific instance of the containing class. * '''<code>final</code>''' - Classes marked as <code>final</code> cannot be extended from and cannot have any subclasses. * '''<code>strictfp</code>''' - Specifies that all floating-point operations must be carried out conforming to [[IEEE 754]] and forbids using enhanced precision to store intermediate results. =====Abstract class===== {{Excerpt|Abstract type #Java}} =====Final class===== {{Excerpt|final (Java)#Final classes}} =====Access modifiers===== 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. <syntaxhighlight lang="java"> public class Foo { int go() { return 0; } private class Bar { } } </syntaxhighlight> 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: {| class="wikitable" style="text-align: center;" !width="20%"|Modifier !width="20%"|Same class or nested class !width="20%"|Other class inside the same package !width="20%"|Extended Class inside another package !width="20%"|Non-extended inside another package |- !<code>private</code> |yes |no |no |no |- !default (package private) |yes |yes |no |no |- !<code>protected</code> |yes |yes |yes |no |- !<code>public</code> |yes |yes |yes |yes |- |} [[File:JavaAccessSpecifier.jpg|thumb|This image describes the class member scope within classes and packages.]] ====Constructors and initializers==== A [[Constructor (object-oriented programming)|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: <syntaxhighlight lang="java"> class Foo { String str; Foo() { // Constructor with no arguments // Initialization } Foo(String str) { // Constructor with one argument this.str = str; } } </syntaxhighlight> 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''. Static initializers initialize static fields when the class is created. They are declared using the <code>static</code> keyword: <syntaxhighlight lang="java"> class Foo { static { // Initialization } } </syntaxhighlight> 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: <syntaxhighlight lang="java"> class Foo { { // Initialization } } </syntaxhighlight> 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 [[method overriding|overridden]] to implement finalization. ====Methods==== All the statements in Java must reside within [[Method (computer programming)|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. <syntaxhighlight lang="java"> class Foo { int bar(int a, int b) { return (a*2) + b; } /* Overloaded method with the same name but different set of arguments */ int bar(int a) { return a*2; } } </syntaxhighlight> 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. <syntaxhighlight 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> The <code>throws</code> keyword indicates that a method throws an exception. All checked exceptions must be listed in a comma-separated list. <syntaxhighlight lang="java"> void openStream() throws IOException, myException { // Indicates that IOException may be thrown } </syntaxhighlight> =====Modifiers===== * '''<code>abstract</code>''' - [[Abstract method]]s can be present only in [[abstract class]]es, such methods have no body and must be overridden in a subclass unless it is abstract itself. * '''<code>static</code>''' - Makes the method static and accessible without creation of a class instance. However static methods cannot access non-static members in the same class. * '''<code>final</code>''' - Declares that the method cannot be overridden in a subclass. * '''<code>native</code>''' - Indicates that this method is implemented through [[JNI]] in platform-dependent code. Actual implementation happens outside Java code, and such methods have no body. * '''<code>strictfp</code>''' - Declares strict conformance to [[IEEE 754]] in carrying out floating-point operations. * '''<code>synchronized</code>''' - Declares that a thread executing this method must acquire monitor. For <code>synchronized</code> methods the monitor is the class instance or <code>java.lang.Class</code> if the method is static. * Access modifiers - Identical to those used with classes. ======Final methods====== {{Excerpt|final (Java)#Final methods}} =====Varargs===== {{Main|Variadic function#In Java}} 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. <syntaxhighlight lang="java"> void printReport(String header, int... numbers) { //numbers represents varargs System.out.println(header); for (int num : numbers) { System.out.println(num); } } // Calling varargs method printReport("Report data", 74, 83, 25, 96); </syntaxhighlight> ====Fields==== Fields, or [[class variable]]s, can be declared inside the class body to store data. <syntaxhighlight lang="java"> class Foo { double bar; } </syntaxhighlight> Fields can be initialized directly when declared. <syntaxhighlight lang="java"> class Foo { double bar = 2.3; } </syntaxhighlight> =====Modifiers===== * '''<code>static</code>''' - Makes the field a static member. * '''<code>final</code>''' - Allows the field to be initialized only once in a constructor or inside initialization block or during its declaration, whichever is earlier. * '''<code>transient</code>''' - Indicates that this field will not be stored during [[serialization]]. * '''<code>volatile</code>''' - If a field is declared <code>volatile</code>, it is ensured that all threads see a consistent value for the variable. ====Inheritance==== Classes in Java can only [[Inheritance (object-oriented programming)|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. <syntaxhighlight lang="java"> class Foo { } class Foobar extends Foo { } </syntaxhighlight> 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. 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: <syntaxhighlight lang="java"> class Foo { public Foo(int n) { // Do something with n } } class Foobar extends Foo { private int number; // Superclass does not have constructor without parameters // so we have to specify what constructor of our superclass to use and how public Foobar(int number) { super(number); this.number = number; } } </syntaxhighlight> =====Overriding methods===== Unlike C++, all non-<code>final</code> methods in Java are [[Virtual function|virtual]] and can be overridden by the inheriting classes. <syntaxhighlight lang="java"> class Operation { public int doSomething() { return 0; } } class NewOperation extends Operation { @Override public int doSomething() { return 1; } } </syntaxhighlight> =====Abstract classes===== An [http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.1 Abstract Class] is a class that is incomplete, or is to be considered incomplete, so cannot be instantiated. A class C has abstract methods if any of the following is true: * C explicitly contains a declaration of an abstract method. * Any of C's superclasses has an abstract method and C neither declares nor inherits a method that implements it. * A direct superinterface of C declares or inherits a method (which is therefore necessarily abstract) and C neither declares nor inherits a method that implements it. * 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. <syntaxhighlight lang="java"> package org.dwwwp.test; /** * @author jcrypto */ public class AbstractClass { private static final String hello; static { System.out.println(AbstractClass.class.getName() + ": static block runtime"); hello = "hello from " + AbstractClass.class.getName(); } { System.out.println(AbstractClass.class.getName() + ": instance block runtime"); } public AbstractClass() { System.out.println(AbstractClass.class.getName() + ": constructor runtime"); } public static void hello() { System.out.println(hello); } } </syntaxhighlight> <syntaxhighlight lang="java"> package org.dwwwp.test; /** * @author jcrypto */ public class CustomClass extends AbstractClass { static { System.out.println(CustomClass.class.getName() + ": static block runtime"); } { System.out.println(CustomClass.class.getName() + ": instance block runtime"); } public CustomClass() { System.out.println(CustomClass.class.getName() + ": constructor runtime"); } public static void main(String[] args) { CustomClass nc = new CustomClass(); hello(); //AbstractClass.hello();//also valid } } </syntaxhighlight> Output: <syntaxhighlight lang="text"> org.dwwwp.test.AbstractClass: static block runtime org.dwwwp.test.CustomClass: static block runtime org.dwwwp.test.AbstractClass: instance block runtime org.dwwwp.test.AbstractClass: constructor runtime org.dwwwp.test.CustomClass: instance block runtime org.dwwwp.test.CustomClass: constructor runtime hello from org.dwwwp.test.AbstractClass </syntaxhighlight> ====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. <syntaxhighlight lang="java"> enum Season { WINTER, SPRING, SUMMER, AUTUMN } </syntaxhighlight> Enum constants are allowed to have constructors, which are called when the class is loaded: <syntaxhighlight lang="java"> public enum Season { WINTER("Cold"), SPRING("Warmer"), SUMMER("Hot"), AUTUMN("Cooler"); Season(String description) { this.description = description; } private final String description; public String getDescription() { return description; } } </syntaxhighlight> Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class: <syntaxhighlight lang="java"> public enum Season { WINTER { String getDescription() {return "cold";} }, SPRING { String getDescription() {return "warmer";} }, SUMMER { String getDescription() {return "hot";} }, FALL { String getDescription() {return "cooler";} }; } </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)