Inheritance and overrides of Java static (static) methods

Source: Internet
Author: User

static method Everyone should be more familiar with, here mainly talk about static methods in the inheritance of some considerations.

1, the parent class method if is static method, the subclass cannot overwrite is the Non-static method;

2, the parent class method if Non-static method, subclasses can not be overridden as a static method;

3. The parent class static method can be overridden to allow static methods with the same name to be defined in subclasses, but not polymorphic.

next to the 3rd feature for a code demo:

Class demo{
public static void display () {
System.out.println ("Hello");
}
}

Class Demotest extends demo{
public static void display () {
System.out.println ("Nihao");
}
}

public class teststaticextend{
public static void Main (String args[]) {
Demo D=new demo ();
D.display ();
D=new demotest ()//Watch the output of this statement, output hello or Nihao
D.display ();
}
}

Analysis: Run the program you will find that the output is two Hello, which is described above "no polymorphism", when you remove the red static and then run will find the output is Hello and Nihao, at this time to restore polymorphism.

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.