What does redefining static methods mean in Java?

前端 未结 3 524
慢半拍i
慢半拍i 2021-02-08 01:08

I\'ve been reading a section on Statics in the SCJP study guide, and it mentions the following :

static methods can\'t be overridden, but they can be r

3条回答
  •  日久生厌
    2021-02-08 01:55

    Static means there is one per class, rather than one per object. This is true for both methods and variables.

    A static field would imply that there is one such field, no matter how many objects of that class are created. Please take a look at Is there a way to override class variables in Java? for the question of overriding a static field. In short: a static field cannot be overridden.

    Consider this:

    public class Parent {
     static int key = 3;
    
     public void getKey() {
      System.out.println("I am in " + this.getClass() + " and my key is " + key);
     }
    }
    
    public class Child extends Parent {
    
     static int key = 33;
    
     public static void main(String[] args) {
      Parent x = new Parent(); 
      x.getKey();
      Child y = new Child();
      y.getKey();
      Parent z = new Child();
      z.getKey();
     }
    }
    
    I am in class tools.Parent and my key is 3
    I am in class tools.Child and my key is 3
    I am in class tools.Child and my key is 3
    

    Key never comes back as 33. However, if you override getKey and add this to Child, then the results will be different.

    @Override public void getKey() {
     System.out.println("I am in " + this.getClass() + " and my key is " + key);
    }
    I am in class tools.Parent and my key is 3
    I am in class tools.Child and my key is 33
    I am in class tools.Child and my key is 33
    

    By overriding the getKey method, you are able to access the Child's static key.

提交回复
热议问题