Skip to main content

Important points on Classes and Methods in Java as per Java Language Specification

Class Declarations:


  • A class declaration specifies a new named reference type.
  • There are two kinds of class declarations: normal class declarations and enum declarations.
  • It is a compile-time error if a class has the same simple name as any of its enclosing classes or interfaces.


Class Modifiers:


  • A class declaration may include class modifiers.
  • The access modifier public pertains only to top level classes and member classes, not to local classes or anonymous classes.
  • The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration.
  • The modifier static pertains only to member classes, not to top level or local or anonymous classes.
  • It is a compile-time error if the same keyword appears more than once as a modifier for a class declaration.


abstract Classes:


  • An abstract class is a class that is incomplete, or to be considered incomplete.
  • It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression.
  • 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.
  • A normal class may have abstract methods, that is, methods that are declared but not yet implemented, only if it is an abstract class. It is a compile-time error if a normal class that is not abstract has an abstract method.


Abstract Class Declaration that Prohibits Subclasses

interface Colorable {
    void setColor(int color);
}
abstract class Colored implements Colorable {
    public abstract int setColor(int color);
}

These declarations result in a compile-time error: it would be impossible for any subclass of class Colored to provide an implementation of a method named setColor, taking one argument of type int, that can satisfy both abstract method specifications, because the one in interface Colorable requires the same method to return no value, while the one in class Colored requires the same method to return a value of type int


final Classes:


  • A class can be declared final if its definition is complete and no subclasses are desired or required.
  • It is a compile-time error if the name of a final class appears in the extends clause of another class declaration; this implies that a final class cannot have any subclasses.
  • It is a compile-time error if a class is declared both final and abstract, because the implementation of such a class could never be completed.
  • Because a final class never has any subclasses, the methods of a final class are never overridden


strictfp Classes:


  • The effect of the strictfp modifier is to make all float or double expressions within the class declaration (including within variable initializers, instance initializers, static initializers, and constructors) be explicitly FP-strict.
  • This implies that all methods declared in the class, and all nested types declared in the class, are implicitly strictfp.


Inner Classes and Enclosing Instances:


  • An inner class is a nested class that is not explicitly or implicitly declared static.
  • An inner class may be a non-static member class, a local class, or an anonymous class. 
  • A member class of an interface is implicitly static so is never considered to be an inner class.
  • It is a compile-time error if an inner class declares a static initializer.
  • It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable.
  • An inner class may inherit static members that are not constant variables even though it cannot declare them.
  • A nested class that is not an inner class may declare static members freely, in accordance with the usual rules of the Java programming language.


Example: Inner Class Declarations and Static Members

class HasStatic {
    static int j = 100;
}
class Outer {
    class Inner extends HasStatic {
        static final int x = 3;  // OK: constant variable
        static int y = 4;  // Compile-time error: an inner class
    }
    static class NestedButNotInner{
        static int z = 5;    // OK: not an inner class
    }
    interface NeverInner {}  // Interfaces are never inner
}

A statement or expression occurs in a static context if and only if the innermost method, constructor, instance initializer, static initializer, field initializer, or explicit constructor invocation statement enclosing the statement or expression is a static method, a static initializer, the variable initializer of a static variable, or an explicit constructor invocation statement.


  • An inner class C is a direct inner class of a class or interface O if O is the immediately enclosing type declaration of C and the declaration of C does not occur in a static context.



  • When an inner class (whose declaration does not occur in a static context) refers to an instance variable that is a member of a lexically enclosing type declaration, the variable of the corresponding lexically enclosing instance is used.


  • Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final , or a compile-time error occurs where the use is attempted.


  • Any local variable used but not declared in an inner class must be definitely assigned before the body of the inner class, or a compile-time error occurs.


  • Similar rules on variable use apply in the body of a lambda expression.


Example. Inner Class Declarations

class Outer {
    int i = 100;
    static void classMethod() {
        final int l = 200;
        class LocalInStaticContext {
            int k = i;  // Compile-time error
            int m = l;  // OK
        }
    }
    void foo() {
        class Local {  // A local class
            int j = i;
        }
    }
}
The declaration of class LocalInStaticContext occurs in a static context due to being within the static method classMethod. Instance variables of class Outer are not available within the body of a static method. In particular, instance variables of Outer are not available inside the body of LocalInStaticContext. However, local variables from the surrounding method may be referred to without error (provided they are marked final).

Inner classes whose declarations do not occur in a static context may freely refer to the instance variables of their enclosing type declaration. An instance variable is always defined with respect to an instance. In the case of instance variables of an enclosing type declaration, the instance variable must be defined with respect to an enclosing instance of that declared type. For example, the class Local above has an enclosing instance of class Outer. As a further example:

class WithDeepNesting {
    boolean toBe;
    WithDeepNesting(boolean b) { toBe = b; }

    class Nested {
        boolean theQuestion;
        class DeeplyNested {
            DeeplyNested(){
                theQuestion = toBe || !toBe;
            }
        }
    }
}
Here, every instance of WithDeepNesting.Nested.DeeplyNested has an enclosing instance of class WithDeepNesting.Nested (its immediately enclosing instance) and an enclosing instance of class WithDeepNesting (its 2nd lexically enclosing instance).

Superclasses and Subclasses:


  • The optional extends clause in a normal class declaration specifies the direct superclass of the current class.
  • The extends clause must not appear in the definition of the class Object, or a compile-time error occurs, because it is the primordial class and has no direct superclass.
  • The ClassType must name an accessible class type, or a compile-time error occurs.
  • It is a compile-time error if the ClassType names a class that is final, because final classes are not allowed to have subclasses.
  • It is a compile-time error if the ClassType names the class Enum or any invocation of Enum.
  • If the ClassType has type arguments, it must denote a well-formed parameterized type, and none of the type arguments may be wildcard type arguments, or a compile-time error occurs.
  • A class is said to be a direct subclass of its direct superclass. The direct superclass is the class from whose implementation the implementation of the current class is derived.
  • The subclass relationship is the transitive closure of the direct subclass relationship. A class A is a subclass of class C if either of the following is true:


A is the direct subclass of C

  • There exists a class B such that A is a subclass of B, and B is a subclass of C, applying this definition recursively.
  • Class C is said to be a superclass of class A whenever A is a subclass of C.


Example: Direct Superclasses and Subclasses

class Point { int x, y; }
final class ColoredPoint extends Point { int color; }
class Colored3DPoint extends ColoredPoint { int z; }  // error

Here, the relationships are as follows:

  • The class Point is a direct subclass of Object.
  • The class Object is the direct superclass of the class Point.
  • The class ColoredPoint is a direct subclass of class Point.
  • The class Point is the direct superclass of class ColoredPoint.
  • The declaration of class Colored3dPoint causes a compile-time error because it attempts to extend the final class ColoredPoint.


Example . Superclasses and Subclasses

class Point { int x, y; }
class ColoredPoint extends Point { int color; }
final class Colored3dPoint extends ColoredPoint { int z; }

Here, the relationships are as follows:

  • The class Point is a superclass of class ColoredPoint.
  • The class Point is a superclass of class Colored3dPoint.
  • The class ColoredPoint is a subclass of class Point.
  • The class ColoredPoint is a superclass of class Colored3dPoint.
  • The class Colored3dPoint is a subclass of class ColoredPoint.
  • The class Colored3dPoint is a subclass of class Point.



  • A class is said to be a direct subclass of its direct superclass. The direct superclass is the class from whose implementation the implementation of the current class is derived.
  • The subclass relationship is the transitive closure of the direct subclass relationship. A class A is a subclass of class C if either of the following is true:
  • A is the direct subclass of C
  • There exists a class B such that A is a subclass of B, and B is a subclass of C, applying this definition recursively.
  • Class C is said to be a superclass of class A whenever A is a subclass of C.


Example. Direct Superclasses and Subclasses

class Point { int x, y; }
final class ColoredPoint extends Point { int color; }
class Colored3DPoint extends ColoredPoint { int z; }  // error

Here, the relationships are as follows:

  • The class Point is a direct subclass of Object.
  • The class Object is the direct superclass of the class Point.
  • The class ColoredPoint is a direct subclass of class Point.
  • The class Point is the direct superclass of class ColoredPoint.
  • The declaration of class Colored3dPoint causes a compile-time error because it attempts to extend the final class ColoredPoint.


Example. Superclasses and Subclasses

class Point { int x, y; }
class ColoredPoint extends Point { int color; }
final class Colored3dPoint extends ColoredPoint { int z; }

Here, the relationships are as follows:


  • The class Point is a superclass of class ColoredPoint.
  • The class Point is a superclass of class Colored3dPoint.
  • The class ColoredPoint is a subclass of class Point.
  • The class ColoredPoint is a superclass of class Colored3dPoint.
  • The class Colored3dPoint is a subclass of class ColoredPoint.
  • The class Colored3dPoint is a subclass of class Point.


 Superinterfaces:


  • The optional implements clause in a class declaration lists the names of interfaces that are direct superinterfaces of the class being declared.
  • Each InterfaceType must name an accessible interface type, or a compile-time error occurs.
  • If an InterfaceType has type arguments, it must denote a well-formed parameterized type, and none of the type arguments may be wildcard type arguments, or a compile-time error occurs.
  • It is a compile-time error if the same interface is mentioned as a direct superinterface more than once in a single implements clause. This is true even if the interface is named in different ways.

Example. Illegal Superinterfaces

class Redundant implements java.lang.Cloneable, Cloneable {
    int x;
}

This program results in a compile-time error because the names java.lang.Cloneable and Cloneable refer to the same interface.

An interface type I is a superinterface of class type C if any of the following is true:

  • I is a direct superinterface of C.
  • C has some direct superinterface J for which I is a superinterface, using the definition of "superinterface of an interface" given in §9.1.3.
  • I is a superinterface of the direct superclass of C.
  • A class can have a superinterface in more than one way.
  • A class is said to implement all its superinterfaces.
  • A class may not at the same time be a subtype of two interface types which are different parameterizations of the same generic interface , or a subtype of a parameterization of a generic interface and a raw type naming that same generic interface, or a compile-time error occurs.


Example . Illegal Multiple Inheritance of an Interface

interface I {}
class B implements I {}
class C extends B implements I {}
Class C causes a compile-time error because it attempts to be a subtype of both I and I.


Example. Illegal Multiple Inheritance of an Interface

interface I {}
class B implements I {}
class C extends B implements I {}
Class C causes a compile-time error because it attempts to be a subtype of both I and I.

Class Members:

The members of a class type are all of the following:

  • Members inherited from its direct superclass, except in class Object, which has no direct superclass
  • Members inherited from any direct superinterfaces.
  • Members declared in the body of the class.
  • Members of a class that are declared private are not inherited by subclasses of that class.
  • Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
  • Constructors, static initializers, and instance initializers are not members and therefore are not inherited.


We use the phrase the type of a member to denote:

  • For a field, its type.
  • For a method, an ordered 4-tuple consisting of:
  • type parameters: the declarations of any type parameters of the method member.
  • argument types: a list of the types of the arguments to the method member.
  • return type: the return type of the method member.
  • throws clause: exception types declared in the throws clause of the method member.

Fields, methods, and member types of a class type may have the same name, since they are used in different contexts and are disambiguated by different lookup procedures. However, this is discouraged as a matter of style.

Example . Use of Class Members

class Point {
    int x, y;
    private Point() { reset(); }
    Point(int x, int y) { this.x = x; this.y = y; }
    private void reset() { this.x = 0; this.y = 0; }
}
class ColoredPoint extends Point {
    int color;
    void clear() { reset(); }  // error
}
class Test {
    public static void main(String[] args) {
        ColoredPoint c = new ColoredPoint(0, 0);  // error
        c.reset();  // error
    }
}
This program causes four compile-time errors.

One error occurs because ColoredPoint has no constructor declared with two int parameters, as requested by the use in main. This illustrates the fact that ColoredPoint does not inherit the constructors of its superclass Point.

Another error occurs because ColoredPoint declares no constructors, and therefore a default constructor for it is implicitly declared, and this default constructor is equivalent to:

ColoredPoint() { super(); }
which invokes the constructor, with no arguments, for the direct superclass of the class ColoredPoint. The error is that the constructor for Point that takes no arguments is private, and therefore is not accessible outside the class Point, even through a superclass constructor invocation.

Two more errors occur because the method reset of class Point is private, and therefore is not inherited by class ColoredPoint. The method invocations in method clear of class ColoredPoint and in method main of class Test are therefore not correct.

Class Members:


  • The members of a class type are all of the following:
  • Members inherited from its direct superclass, except in class Object, which has no direct superclass
  • Members inherited from any direct superinterfaces
  • Members declared in the body of the class
  • Members of a class that are declared private are not inherited by subclasses of that class.
  • Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
  • Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
  • We use the phrase the type of a member to denote:
  • For a field, its type.
  • For a method, an ordered 4-tuple consisting of:
  • type parameters: the declarations of any type parameters of the method member.
  • argument types: a list of the types of the arguments to the method member.
  • return type: the return type of the method member.
  • throws clause: exception types declared in the throws clause of the method member.
  • Fields, methods, and member types of a class type may have the same name, since they are used in different contexts and are disambiguated by different lookup procedures. However, this is discouraged as a matter of style.


Example Use of Class Members

class Point {
    int x, y;
    private Point() { reset(); }
    Point(int x, int y) { this.x = x; this.y = y; }
    private void reset() { this.x = 0; this.y = 0; }
}
class ColoredPoint extends Point {
    int color;
    void clear() { reset(); }  // error
}
class Test {
    public static void main(String[] args) {
        ColoredPoint c = new ColoredPoint(0, 0);  // error
        c.reset();  // error
    }
}
This program causes four compile-time errors.

One error occurs because ColoredPoint has no constructor declared with two int parameters, as requested by the use in main. This illustrates the fact that ColoredPoint does not inherit the constructors of its superclass Point.

Another error occurs because ColoredPoint declares no constructors, and therefore a default constructor for it is implicitly declared , and this default constructor is equivalent to:

ColoredPoint() { super(); }

which invokes the constructor, with no arguments, for the direct superclass of the class ColoredPoint. The error is that the constructor for Point that takes no arguments is private, and therefore is not accessible outside the class Point, even through a superclass constructor invocation (§8.8.7).

Two more errors occur because the method reset of class Point is private, and therefore is not inherited by class ColoredPoint. The method invocations in method clear of class ColoredPoint and in method main of class Test are therefore not correct.


Example. Inheritance of Class Members with Package Access

Consider the example where the points package declares two compilation units:

package points;
public class Point {
    int x, y;
    public void move(int dx, int dy) { x += dx; y += dy; }
}
and:

package points;
public class Point3d extends Point {
    int z;
    public void move(int dx, int dy, int dz) {
        x += dx; y += dy; z += dz;
    }
}
and a third compilation unit, in another package, is:

import points.Point3d;
class Point4d extends Point3d {
    int w;
    public void move(int dx, int dy, int dz, int dw) {
        x += dx; y += dy; z += dz; w += dw; // compile-time errors
    }
}

Here both classes in the points package compile. The class Point3d inherits the fields x and y of class Point, because it is in the same package as Point. The class Point4d, which is in a different package, does not inherit the fields x and y of class Point or the field z of class Point3d, and so fails to compile.

A better way to write the third compilation unit would be:

import points.Point3d;
class Point4d extends Point3d {
    int w;
    public void move(int dx, int dy, int dz, int dw) {
        super.move(dx, dy, dz); w += dw;
    }
}

using the move method of the superclass Point3d to process dx, dy, and dz. If Point4d is written in this way, it will compile without errors.


Example . Inheritance of public and protected Class Members

Given the class Point:

package points;
public class Point {
    public int x, y;
    protected int useCount = 0;
    static protected int totalUseCount = 0;
    public void move(int dx, int dy) {
        x += dx; y += dy; useCount++; totalUseCount++;
    }
}

the public and protected fields x, y, useCount, and totalUseCount are inherited in all subclasses of Point.

Therefore, this test program, in another package, can be compiled successfully:

class Test extends points.Point {
    public void moveBack(int dx, int dy) {
        x -= dx; y -= dy; useCount++; totalUseCount++;
    }
}

Example . Inheritance of private Class Members

class Point {
    int x, y;
    void move(int dx, int dy) {
        x += dx; y += dy; totalMoves++;
    }
    private static int totalMoves;
    void printMoves() { System.out.println(totalMoves); }
}
class Point3d extends Point {
    int z;
    void move(int dx, int dy, int dz) {
        super.move(dx, dy); z += dz; totalMoves++; // error
    }
}

Here, the class variable totalMoves can be used only within the class Point; it is not inherited by the subclass Point3d. A compile-time error occurs because method move of class Point3d tries to increment totalMoves.


Example. Accessing Members of Inaccessible Classes

Even though a class might not be declared public, instances of the class might be available at run time to code outside the package in which it is declared by means of a public superclass or superinterface. An instance of the class can be assigned to a variable of such a public type. An invocation of a public method of the object referred to by such a variable may invoke a method of the class if it implements or overrides a method of the public superclass or superinterface. (In this situation, the method is necessarily declared public, even though it is declared in a class that is not public.)

Consider the compilation unit:

package points;
public class Point {
    public int x, y;
    public void move(int dx, int dy) {
        x += dx; y += dy;
    }
}
and another compilation unit of another package:

package morePoints;
class Point3d extends points.Point {
    public int z;
    public void move(int dx, int dy, int dz) {
        super.move(dx, dy); z += dz;
    }
    public void move(int dx, int dy) {
        move(dx, dy, 0);
    }
}
public class OnePoint {
    public static points.Point getOne() { 
        return new Point3d(); 
    }
}

An invocation morePoints.OnePoint.getOne() in yet a third package would return a Point3d that can be used as a Point, even though the type Point3d is not available outside the package morePoints. The two-argument version of method move could then be invoked for that object, which is permissible because method move of Point3d is public (as it must be, for any method that overrides a public method must itself be public, precisely so that situations such as this will work out correctly). The fields x and y of that object could also be accessed from such a third package.

While the field z of class Point3d is public, it is not possible to access this field from code outside the package morePoints, given only a reference to an instance of class Point3d in a variable p of type Point. This is because the expression p.z is not correct, as p has type Point and class Point has no field named z; also, the expression ((Point3d)p).z is not correct, because the class type Point3d cannot be referred to outside package morePoints.

The declaration of the field z as public is not useless, however. If there were to be, in package morePoints, a public subclass Point4d of the class Point3d:

package morePoints;
public class Point4d extends Point3d {
    public int w;
    public void move(int dx, int dy, int dz, int dw) {
        super.move(dx, dy, dz); w += dw;
    }
}
then class Point4d would inherit the field z, which, being public, could then be accessed by code in packages other than morePoints, through variables and expressions of the public type Point4d.


Field Declarations:


  • The variables of a class type are introduced by field declarations.
  • It is a compile-time error for the body of a class declaration to declare two fields with the same name.
  • If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
  • A hidden field can be accessed by using a qualified name if it is static, or by using a field access expression that contains the keyword super or a cast to a superclass type.
  • A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.
  • A private field of a superclass might be accessible to a subclass - for example, if both classes are members of the same class. Nevertheless, a private field is never inherited by a subclass.
  • It is possible for a class to inherit more than one field with the same name. Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.


Field Modifiers:


  • It is a compile-time error if the same keyword appears more than once as a modifier for a field declaration.
  • If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.


static Fields:


  • If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized.
  • A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.


final Fields:


  • A field can be declared final. Both class and instance variables (static and non-static fields) may be declared final.
  • A blank final class variable must be definitely assigned by a static initializer of the class in which it is declared, or a compile-time error occurs.
  • A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared, or a compile-time error occurs


transient Fields:


  • Variables may be marked transient to indicate that they are not part of the persistent state of an object.

Example. Persistence of transient Fields
If an instance of the class Point:

class Point {
    int x, y;
    transient float rho, theta;
}

were saved to persistent storage by a system service, then only the fields x and y would be saved. This specification does not specify details of such services; see the specification of java.io.Serializable for an example of such a service.

volatile Fields:


  • The Java programming language allows threads to access shared variables. As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.
  • The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.
  • A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable.
  • It is a compile-time error if a final variable is also declared volatile.


If, in the following example, one thread repeatedly calls the method one (but no more than Integer.MAX_VALUE times in all), and another thread repeatedly calls the method two:

class Test {
    static int i = 0, j = 0;
    static void one() { i++; j++; }
    static void two() {
        System.out.println("i=" + i + " j=" + j);
    }
}
then method two could occasionally print a value for j that is greater than the value of i, because the example includes no synchronization and, under the rules explained in, the shared values of i and j might be updated out of order.

One way to prevent this out-or-order behavior would be to declare methods one and two to be synchronized:

class Test {
    static int i = 0, j = 0;
    static synchronized void one() { i++; j++; }
    static synchronized void two() {
        System.out.println("i=" + i + " j=" + j);
    }
}
This prevents method one and method two from being executed concurrently, and furthermore guarantees that the shared values of i and j are both updated before method one returns. Therefore method two never observes a value for j greater than that for i; indeed, it always observes the same value for i and j.

Another approach would be to declare i and j to be volatile:

class Test {
    static volatile int i = 0, j = 0;
    static void one() { i++; j++; }
    static void two() {
        System.out.println("i=" + i + " j=" + j);
    }
}

This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread. Therefore, the shared value for j is never greater than that for i, because each update to i must be reflected in the shared value for i before the update to j occurs. It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i, because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j.


Method Declarations:


  • A method declares executable code that can be invoked, passing a fixed number of values as arguments.


abstract Methods:


  • An abstract method declaration introduces the method as a member, providing its signature, result, and throws clause if any, but does not provide an implementation. A method that is not abstract may be referred to as a concrete method.
  • The declaration of an abstract method m must appear directly within an abstract class (call it A) unless it occurs within an enum declaration; otherwise a compile-time error occurs.
  • Every subclass of A that is not abstract must provide an implementation for m, or a compile-time error occurs.
  • An abstract class can override an abstract method by providing another abstract method declaration.
  • This can provide a place to put a documentation comment, to refine the return type, or to declare that the set of checked exceptions that can be thrown by that method, when it is implemented by its subclasses, is to be more limited.
  • An instance method that is not abstract can be overridden by an abstract method.


static Methods:

  • A method that is declared static is called a class method.
  • It is a compile-time error to use the name of a type parameter of any surrounding declaration in the header or body of a class method.
  • A class method is always invoked without reference to a particular object. It is a compile-time error to attempt to reference the current object using the keyword this or the keyword super.
  • A method that is not declared static is called an instance method, and sometimes called a non-static method.
  • An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.


final Methods:


  • A method can be declared final to prevent subclasses from overriding or hiding it.
  • It is a compile-time error to attempt to override or hide a final method.
  • A private method and all methods declared immediately within a final class behave as if they are final, since it is impossible to override them.


native Methods:


  • A method that is native is implemented in platform-dependent code, typically written in another programming language such as C. The body of a native method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.

For example, the class RandomAccessFile of the package java.io might declare the following native methods:

package java.io;
public class RandomAccessFile
    implements DataOutput, DataInput {
    . . .
    public native void open(String name, boolean writeable)
        throws IOException;
    public native int readBytes(byte[] b, int off, int len)
        throws IOException;
    public native void writeBytes(byte[] b, int off, int len)
        throws IOException;
    public native long getFilePointer() throws IOException;
    public native void seek(long pos) throws IOException;
    public native long length() throws IOException;
    public native void close() throws IOException;
}

strictfp Methods:


  • The effect of the strictfp modifier is to make all float or double expressions within the method body be explicitly FP-strict


synchronized Methods:


  • A synchronized method acquires a monitor before it executes.
  • For a class (static) method, the monitor associated with the Class object for the method's class is used.
  • For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

synchronized Monitors
These are the same monitors that can be used by the synchronized statement
Thus, the code:

class Test {
    int count;
    synchronized void bump() {
        count++;
    }
    static int classCount;
    static synchronized void classBump() {
        classCount++;
    }
}

has exactly the same effect as:

class BumpTest {
    int count;
    void bump() {
        synchronized (this) { count++; }
    }
    static int classCount;
    static void classBump() {
        try {
            synchronized (Class.forName("BumpTest")) {
                classCount++;
            }
        } catch (ClassNotFoundException e) {}
    }
}


  • A throws clause is used to declare any checked exception classes that the statements in a method or constructor body can throw.
  • It is a compile-time error if an ExceptionType mentioned in a throws clause is not a subtype of Throwable.
  • Type variables are allowed in a throws clause even though they are not allowed in a catch clause.
  • It is permitted but not required to mention unchecked exception classes in a throws clause.

Comments

Popular posts from this blog

StackOverFlowError and OutOfMemoryError in java

There are two area inside java virtual machine's memory the heap and the  stack . The  stack  memory is used to store local variables and function call while heap memory is used to store objects in  Java The most common cause of StackOverFlowError is too deep or infinite recursion or many local objects / variables creation inside function call in  Java.  According to the java source documentation,  Java throws  java.lang.StackOverflowError   when a stack overflow occurs because an application recurses too deeply. JVM has a given memory allocation for each stack of each thread, and if an attempt to call a method happens to fill this memory, JVM throws an error. Just like it would do if we try to write at index N of an array of length N.  The point to be noted here is that - These are errors not an exceptions. No memory corruption happens due to the error. Stack can not write into the heap space. A StackOverflowError i...

Job Sequencing with Deadlines

Given a set of n jobs Each job i has an integer deadlines di>=0 and a profit pi>0 All jobs requires only one unit time to complete Only one machine is available for processing jobs For job i the profit pi is earned if the job is completed by its deadline.