A
A
Artem2021-10-23 16:52:21
Java
Artem, 2021-10-23 16:52:21

Static members don't copy their data even in descendants?

class A {
  public static int i = 10;
  public static void printI() {
    System.out.println(i);
  }
}

class B extends A {
  public static void changeI() {
    i++;
  }
}

public class Main {
  public static void main(String[] args) {
    A a = new A();
    B b = new B();
    
    a.printI();
    b.printI();
    
    b.changeI();
    
    a.printI();
    b.printI();
  }
}


Output:
10
10
11
11

I was just wondering why enum needs valueOf(). Understood. I assumed that the method stores the string representation of the constants, and then compares the input data with them. But since I know that the constants in enum are anonymous classes, it seemed unoptimized to me that this method is also available in them (inherited). At first I thought that the inheritance of implicit methods is controlled by java. Perhaps this is so.

It turns out that I really have to override these variables with a repeated declaration to break the connection with the ancestor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vamp, 2021-10-23
@Trame2771

Static members are not inherited, right. Because it's pointless.

I just thought why is it needed in enum valueOf(). Understood. I assumed that the method stores the string representation of the constants, and then compares the input data with them.

The valueOf() method does not store anything and the compiler substitutes the same implementation of valueOf() in all enums:
public enum Hello {
    FIZZ, BUZZ;

    // Данный метод автоматически генерируется компилятором.
    // Для любого enum'а.
    public static Hello valueOf(String name) {
        return Enum.valueOf(Hello.class, name);
    }
}

And inside Enum.valueOf is the usual HashMap<String, Hello> , where the key is the name of the constant, and the value is the corresponding instance of the Hello class. I can not agree that this option is bad in terms of optimization.
But since I know that enum constants are anonymous classes

This is not true. Constants are concrete instances of your enum class, not instances of anonymous inheritors from it.
It turns out that I really have to override these variables with a repeated declaration to break the connection with the ancestor?

I didn't really understand the point of the question. To break the connection with the ancestor, you just need to remove the inheritance from it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question