'Does in Java an implementing class inherits the interface constants or not? [closed]

I am asking myself, if an interface in Java inherits its constants or not?!

I am just reading the "OCP Java SE Programmer II Exam Guide" (Oracle Press, ISBN: 978-1-260-11738-7) and they are writing:

  1. "you can create inheritance relationships in Java by extending a class or by implementing an interface" (page 76)
  2. "any class that implements the interface has direct access to the constants, just as if the class had inherited them" (page 12)

Isn't it a contradiction?

Example:

public interface InterfaceA2 {

    int NUMBER = 100;
}

class A2 {
    
    public static void main(String[] args) {
        
        // System.out.println(NUMBER);  // compiler error
        System.out.println(InterfaceA2.NUMBER);
    }
}

class B2 implements InterfaceA2 {
    
    public static void main(String[] args) {
        System.out.println(NUMBER); // <------------------ looks like inheritance?!
        System.out.println(InterfaceA2.NUMBER);
    }
}


Solution 1:[1]

It all boils down to the question how you define the term "inheritance".

  • An instance of a class can be called not only with its own methods, but also with all methods declared in any of its superclasses. Would you like to call that "inheritance"? The Java community does so.

  • An instance of a class does not only have the fields that it declared itself, but also all fields declared in any of its superclasses. Would you like to call that "inheritance"? The Java community does so.

  • A subclass implicitly has all the characteristics of its superclass, e.g. which interfaces it implements. Would you like to call that "inheritance"? The Java community does so.

  • A class implementing an interface will have all the methods declared in the interface. Would you like to call that "inheritance"? The Java community calls this "implementing an interface", not "inheritance". [I'm a bit surprised that the Oracle book seems to use the term "inheritance" here as well.]

  • In a class implementing an interface, you can access constants declared in the interface by their simple name, without the need to prefix the constant with the interface name. Would you like to call that "inheritance"? The Java community does not, it's just a shorthand notation.

  • When importing a package like import java.awt.*, you can then access classes by their simple name, without the need to prefix them with their package name. Would you like to call that "inheritance"? The Java community does not, it's just a shorthand notation.

Of course, you can call any of these (and many more) language features by any name you like, but don't be surprised if it causes misunderstandings.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ralf Kleberhoff