Today, I was asked this question by the intern :

stay java in ,static Can member functions be overridden ?

The conclusion is that , You can override one in a subclass static function , But this function doesn't look like a normal non static Function .

in other words , Although you can define an override function , But the function has no polymorphism . Let's test it out :

 1 class testClass1{
2 static void SMethod(){
3 System.out.println("static in testClass1");
4 }
5 }
6 class testClass2 extends testClass1{
7 static void SMethod(){
8 System.out.println("static in testClass2");
9 }
10 }
11 public class MainClass{
12 public static void main(String... args){
13 testClass1 tc1=new testClass2();
14 testClass2 tc2 =new testClass2();
15 tc1.SMethod(); // The output is static in testClass1
16 tc2.SMethod(); // The output is static in testClass2
17 }
18 }

You can see from the results , When we use instances of the parent class to refer to ( In fact, the instance is a subclass ) call static Function time , Called by the parent class static function .

The reason is the order in which the methods are loaded .

When a method is called ,JVM First check if it is a class method . If it is , Then directly find the method from the class of the reference variable calling the method and execute , It's no longer sure if it's rewritten ( Cover ). If not , To do something else ( For example, dynamic method query )

Maybe someone slaps on the thigh , Isn't that what java Static / Dynamic dispatch !

It's kind of like , But not really , Static and dynamic dispatch are used to determine overloading and rewriting logic . In the process of overloading , The compiler depends on the static type of the method parameter ( such as tc1 The static type of is class1,tc2 Yes. class2, But this article is not overload !) To determine the version of the usage , This is called static dispatch . Dynamic dispatch is used for method rewriting , For example, I call a class A Methods f, If the class has subclasses a, Then I to a To call f When , The actual call is a.f Instead of A.f.

It really looks like dynamic dispatch, doesn't it ? But the results don't match !

The reason for this is , Dynamic dispatch , We're actually talking about Java Of invokevirtual The act of command : This instruction first looks for the runtime type of the caller , Then find the matching method in its method table , If you can't find it , And then find it from its parent class . This process is Java The nature of method rewriting in , That's dynamic dispatch .

and static The way is through invokestatic Command to call . because static Method is a compile time method , An immutable method of operation , So as far as the pipe class and the parent class have the same method name , And in fact they're different ways , It's also a completely distinguishable way . Calling static When the method is used , The compiler resolves the symbolic reference to a direct reference when the class is loaded , There is no such behavior as going to the parent class to find the method after the subclass can't find it , So it's also called parse call .

That's why the method that looks like rewriting in the above example doesn't produce the effect of rewriting .

The full text after .

from Java Duplicate names of inherited classes static Function analysis call and dispatch more related articles

  1. C++ Class inheritance four ( Duplicate members in class inheritance )

    // Duplicate members in class inheritance #include<iostream> using namespace std; /* I guess : For members in a subclass with the same name as the parent class ,c++ The compiler will change for this member of the subclass ...

  2. java Inheritance class and interface problems

    java First extends Inheritance class , Again implements Inherited interface public class DataBase extends ClassBase implements Ijiekou { }// ...

  3. In depth understanding of java virtual machine ( 11、 ... and ) Method call - Parsing calls and dispatching calls

    Method calling process is to determine the version of the called method ( That is, which method to call ), Does not include method execution . We know ,Class The file compilation process does not include the connection steps in the traditional compilation , All method calls are in Class All that's stored in file calls is ...

  4. [Java][Android][Process] Process establish + control + analysis Experience talks about

    Whether it's Android Also, or Java It is more or less necessary to call some of the underlying commands in . Run some parameters : Now we need to use Java Of Process To create a subprocess . It's a child process because it depends on the process that initiated the create request , Hypothetical hair ...

  5. java The first letter of the attribute name of an entity class cannot be capitalized , Otherwise el Expression cannot take value

    Abstract :Java In the naming convention , Entity class property names start with lowercase letters , But it doesn't say you can't start with a capital letter , But the truth is , Big photo is not good

  6. java Get the full class name of the class ---- Class name .class.getName() The function of is to get the full class name of this class

    Class name .class.getName() The function of is to get the full class name of this class

  7. java After inheriting a class , The reasons and solutions for not being able to access the properties of the superclass

    It's because the properties in the superclass don't add public keyword resolvent :  If the properties or methods in superclass and superclass want to be called by methods under other packages , You have to add all of them public jurisdiction , That is, set it to public access example : @Controller publ ...

  8. java File Class and some functions

    package file; import; import; import org.junit.jupiter.api.Test; /* ...

  9. Inherit the virtual function c++ class , Inheritance class , Classes with virtual functions , Memory layout of virtual inherited classes , Use vs2010 Print layout results .

    When I was shopping in Qingdao, I suddenly thought of ... Recently, I want to write a few notes about inheriting virtual functions , So when I got home, I wrote and published it application sizeof The problem of function class size is very common in many interviews , It's easy to test in the oral test , When it comes to classes ...

Random recommendation

  1. VIP

    High availability HA(High Availability) It refers to by minimizing routine maintenance operations ( plan ) And sudden system crashes ( Unplanned ) The resulting downtime , To improve system and application availability .HA The system is the core computer system of current enterprises ...

  2. Win7 Quick Launch bar 1. Right click on the taskbar -> The toolbar -> New toolbar .   stay ...

  3. Use javascript Open a new page without being blocked by the browser

    Use javascript There are several ways to open a new page , But each has its advantages and disadvantages , Here's an analysis This is the most common method for novices , The advantage is that it's easy to use , Disadvantage , It's simple , It will be intercepted by many browsers, resulting in loss of function ...

  4. On labor day, the brain is opening up ! utilize Debug API obtain Shell client's MD5 value

    System : Windows xp Program :  A game client Program download address : Does not provide requirement : Remote injection & obtain MD5 value Using tools : vc++6.0 & OD Case description : The game client is right ...

  5. EV Battery index and characteristics

    In the battery family , There are many kinds of batteries , The common feature is that you can experience multiple charges . Discharge cycle , Repeated use , This is also the basis of battery as the power source of electric vehicles . Of course , Not all batteries are suitable for electric vehicles , From the global development of new energy vehicles ...

  6. js— object

    One . Create objects var car = new Object(); var car = {}; Two . Properties and methods var car = { color : "red", run : func ...

  7. GreenDao Translation of official documents ( Next )

    Chapter five Inquire about Queries return entities that meet certain criteria . You can use the original SQL Custom query statement , Or better : Use GreenDao Of QueryBuilder API. The query also supports lazy-loading The result set ...

  8. debug(fmt,args...) debugging

    1. Defining macro (debug.h) #ifndef __DEBUG__H #define __DEBUG__H #include <stdio.h> #ifdef DEBUG #define d ...

  9. Spark Executor Driver Resource scheduling summary 【 turn 】

    One . Introduction stay Worker Actor in , Every time LaunchExecutor Will create a CoarseGrainedExecutorBackend process ,Executor and CoarseGrainedExecut ...

  10. crossdomain.xml stride across

    crossdomain.xml yes adobe Engaged in , In order to make flash Cross domain access to files . The configuration file is placed under the root directory of the server . To set which domain names to use swf Files can access the content on my server . such as : I have a graph on my server ...