Difference between static and final method in java

Static methods can be overriden, but they cannot be overriden to be non-static,Whereas final methods cannot be overridden.

A static method is a method that’s invoked through a class, rather than a specific object of that class. Static methods can only access static variables – they can’t use anything that’s specific to a particular object. Nonstatic methods (or instance methods) must be called on a specific object and can use the object’s instance data.
A final method is just a method that cannot be overridden – while static methods are implicitly final, you might also want to create an final instance method.

In this code:

class Foo {
    public static void method() {
        System.out.println("in Foo");
    }
} 

class Bar extends Foo {
    public static void method() {
        System.out.println("in Bar");
    }
}

the static method in Bar ‘hides’ the static method declared in Foo, as opposed to overriding it in the polymorphism sense.

class Test {
public static void main(String[] args) {

        Foo.method();
        Bar.method();
    }
}

will output:

in Foo
in Bar

Re-defining method() as final in Foo will disable the ability for Bar to hide it, and re-running main() will output:

in Foo
in Foo

Compilation fails when you mark the method as final, and only runs again when remove Bar.method()

Final will prevent the method from being hidden by subclasses .

One Thought on “Difference between static and final method in java

  1. I read a lot of interesting content here. Probably you spend a
    lot of time writing, i know how to save you a lot of work, there
    is an online tool that creates high quality, google friendly articles in seconds, just search in google –
    laranitas free content source

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation