RSS Feed

Java Method

A Java method is a set of Java statements that can be included inside a Java class.

Java methods are similar to functions or procedures in other programming languages.

There are many different types of Java methods:

Final Method
Public Method
Private Method
Package Method
Instance Method
Protected Method
Static Method
Main Method

The Main Method

Every Java program must have one main method. The main method is the first method which the Java Virtual Machine executes. The main method then calls the other methods, as they are needed. Main method is often written as main() method.

Here is the main() method from a Java program that prints “Hello World:”

public static void main (String[] args) {
// This Java program prints "Hello World!"
System.out.println{"Hello World!");
}

It is good programming practice to maintain a very small main method and to move all possible code into other methods.

 Java Method

Instance Method

An instance method is a method which is associated with one object and uses the instance variables of that object.

The opposite of an instance method is a static method.

The default for a method is to be an instance method.

Static Method

A static method is a Java method which accepts arguments instead of using instance variables.

The opposite of a static method is an instance method.

The default for a method is to be an instance method. Methods must be explicitly defined as static methods.

A static method is also referred to as a class method.

Package Method

A package method can be called by any class within its package.

This is the default access level if no access level is explicity declared.

The other options for declaring visibility are private, public, and protected.

Private Method

A private method is a method which is not inherited by subclasses.

Declaring a method private defines its access level.

The other options for declaring visibility are public and protected.

If undeclared, the default access level is package.

Protected Method

A protected method can be called by any subclass within its class, but not by unreleated classes.

Declaring a method protected defines its access level.

The other options for declaring visibility are private and public.

If undeclared, the default access level is package.

Public Method

A public method is a method which can be called by any object.

Declaring a method public defines its access level.

The other options for declaring visibility are private and protected.

If undeclared, the default access level is package.

Final Method

A final method is a method which cannot be overridden by a subclass.

Leave a Reply

Post your comments and questions below, but please follow our commenting guidelines.


Path: Home > Programming > Java > Java Method