Can a static method in Java be overridden?

Source: Internet
Author: User

* The non-static method belongs to the class instance, can be overridden by the quilt class, thus achieves the polymorphic effect;
Static methods belong to classes and cannot be rewritten, and therefore polymorphic. *

The following is a concrete verification process

First, define a superclass, a, inside a static method and a non-static method:

public class A {    public void unstaticMethod() { System.out.println("SuperClass unstaticMethod"); } public static void staticMethod() { System.out.println("SuperClass staticMethod"); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

Next, define a subclass B, which defines a static method and a non-static method (formally like a method that overrides a superclass):

public class B extends A { public void unstaticMethod() { System.out.println("SunClass unstaticMethod"); } public static void staticMethod() { System.out.println("SunClass staticMethod"); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

In the next step, we test:

public class Test {    @SuppressWarnings("static-access")    public static void main(String[] args) { A a = new A(); A a2 = new B(); a.unstaticMethod(); a2.unstaticMethod(); a.staticMethod(); a2.staticMethod(); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

Operation Result:

SuperClass unstaticMethodSunClass unstaticMethodSuperClass staticMethodSuperClass staticMethod
    • 1
    • 2
    • 3
    • 4
    • 5
    • 1
    • 2
    • 3
    • 4
    • 5

From the running result, we can know that for the non-static method, the effect of polymorphism is realized, but the static method is not.

Can a static method in Java be overridden?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.