CSS font stacks, developer FAQs & web standards

Your banner ad here

WestNIC provides reliable web hosting services

Top Canadian Hotels no booking fees from Victoria BC to Nova Scotia

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.

Static design principles

Q: When should I use static operations?

A: Java is an object oriented language, so the first principle is to implement the majority of your program through object instances, instance variables and methods. One area where a static context is necessary is during program start-up because the Java entry point method is static: public static void main(String[]). This means that variables and methods required during start-up may need to be static too, but the principle should be to create a primary core object for your program early and use that to instantiate and interact with other object components of the system.

As a rule, static variables and methods should be kept to a minimum. Static variables are generally used for values that belong to, or represent some state of the class as a whole, where all instances would have the same value. The most obvious examples are constants like Integer.MAX_VALUE, where the value is fixed and standard whatever instance of an Integer you have, or a counter that keeps track of a value across all instances.

Static methods are often used as utilities that are not associated with a particular instance of a class. For example, static utility methods may be used to parse an input value to another type, as with the Integer.valueOf(String) method, or as so-called factory methods to acquire a pre-configured instance of a type, like the Calendar.getInstance() method.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Static variables

Q: What is special about static variables?

A: A static variable is shared by all instances of a class. Every instance has a reference to the same variable and can modify it directly. Static instances are declared with the static modifier.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
What is special about static variables?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: I get "non-static variable this cannot be referenced from a static context"!

A: The main method must be declared public static void because it is invoked when the Java Virtual Machine first starts up, before any Java object instances exist. The main method may reference any number of static variables and call static methods. Any series of calls to other static methods only extends this original static context. To reference a non-static or instance variable from the main method, you must first instantiate the relevant object, even if it is the host of the main method itself, as below.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
I get "non-static variable this cannot be referenced from a static context"!

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I call static class members from a different class?

A: Calling static members in a separate class is very similar to calling a static method in a separate class. Most importantly, the static member must have a public, package or protected modifier that makes it accessible to the calling class. Use the class name, a dot separator and the name of the member variable, as with the AWT Color class properties below:

Color textColor = Color.black;
Color panelColor = Color.lightGray;
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Static method calls

Q: What's the difference in calling a method from a class or an object?

A: The only way that a class can call a method without an object reference is in a static context. For example, the static main() method is invoked in a static context, before any instance is created, so any methods it calls must also be static. The main() method may call static methods of its own, or of other classes.

One key thing about static methods is that they must not reference any instance variables or call any instance methods because there may not be any instance of an object in the static context.

When you call a method from an object (more precisely from a reference to an instance of an object), it ensures that an instance exists and means that all instance variables are initialised and can be referenced, and instance methods can safely be called. The compiler ensures these conditions. An instance can also call a class or static method and variables of its own or other classes.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How do I call a static method in a separate class?

A: To call a static method in a separate class you should prefix the method reference with the name of the class it belongs to, known as the host class. For example, the String class has valueOf() methods to convert primitive values to strings:

String booleanString = String.valueOf(true);
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I call a static method from an object reference?

A: Yes, it is possible to call a static method on an object reference using the same dot syntax as for a static class reference, as below.

String stringRef = "Example";

System.out.println(stringRef.valueOf(true));
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I call super() from a static context?

A: The super() method can only be called in an object's constructor, it cannot be called in a static context. The only way to invoke the super() method is to place this statement in the first line of an object's constructor and instantiate the object. You can then invoke this method via the static void main(String[]) method, as below.

public class SuperConstructor extends Superclass {

  public SuperConstructor() {

    super();
  }

  public static void main(String[] args) {

    SuperConstructor object = new SuperConstructor();
  }
}
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I call the superclass version of an overridden static method?

A: Static methods cannot truly be overridden, if you create static methods with the same signature as those in a superclass it will lead to confusing behaviour and is not recommended. It is not possible to use the super keyword in the static context of a subclass because it refers to a instance. Just use the standard static method reference scheme for the superclass; the superclass name, a dot separator, the method name and arguments, as below.

public class ExampleSubclass extends ExampleSuperclass {

    public static void main(String[] args) {

        ExampleSuperclass.testMethod();
    }
}
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: This static method sure looks like it overrides the superclass!

A: Creating a static method with the same signature as a superclass version effectively hides the superclass method, it does not override it. This is a difficult distinction to understand and to detect because in several contexts the methods behave as if they were overridden. The difference becomes apparent when an instance of the subclass is assigned to a superclass type, as below.

public class SuperclassStatic {

    public static void testMethod() {

        System.out.println("Superclass message");
    }
}

public class SubclassStatic extends SuperclassStatic {

    public static void testMethod() {

        System.out.println("Subclass message");
    }

    public static void main(final String[] args) {

        System.out.println("Calling subclass method...");
        testMethod();

        System.out.println("Calling superclass method...");
        SuperclassStatic.testMethod();

        // Subclass type
        SubclassStatic subStatic = new SubclassStatic();

        System.out.println("Calling static method on subclass type...");
        subStatic.testMethod();

        // Superclass type
        SuperclassStatic superStatic = new SubclassStatic();

        System.out.println("Calling static method on superclass type...");
        superStatic.testMethod();
    }
}
      

The subclass' local call to the static testMethod() executes its own version and you get the subclass message. The call to the SuperclassStatic.testMethod() executes the superclass version and you get the superclass message.

When you assign an instance of the subclass to a SubclassStatic type variable, the runtime system executes the testMethod() version associated with the variable type, so gives the subclass message. In the last case a subclass instance is assigned to a variable declared as a SuperStatic type, so the testMethod() defined in the superclass is executed and gives the superclass message.

The Java compiler does not fail or warn about static method name clashes, so it is important to be aware of this scenario and avoid it.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

The static modifier

Q: What is the difference between static and final keywords?

A: The static and final modifiers have quite distinct purposes in Java, though they can be used in combination to declare class constants. When the static modifier is applied to a variable or method it belongs to all instances of the class and can be referenced in a static context. In other words, the class does not have to be instantiated before the variable can be read or the method called. That means that static variables must be assigned at compile time and static methods cannot reference instance variables or call instance methods.

The final modifier can be applied to a class definition or method to prevent extension or overriding respectively. This helps the compiler optimise byte code for the class. When the final modifier is declared on a variable it means that its initial assignment will not change during the execution of the code. Final instance variables must be assigned at compile time or in the class' constructor, as in the example below.

premium content omitted

Sign up for premium content now Access all premium content for $50: sign-up now.
What is the difference between static and final keywords?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Add this page to your chosen social bookmarking service

Style warning, please read

Home · CSS · Java · Javascript · HTML · Help · Log