0

(Context: I'm coming from a Python world and just re-learning my way around Java. Go gentle on me!)

Imagine I'd like the following effect from my Java program:

> SpacelySprockets.getName() => "Spacely Sprockets, Inc."
> CogswellCogs.getName() => "Cogswell Cogs Corp."

I know the following isn't legal Java, but I'd imagine a structure along these lines:

public class Manufacturer {
    public static String getName() { return COMPANY_NAME; }
}
public class SpacelySprockets extends Manufacturer {
    public static String COMPANY_NAME = "Spacely Sprockets, Inc.";
}
public class CogswellCogs extends Manufacturer {
    public static String COMPANY_NAME = "Cogswell Cogs Corp.";
}

(FWIW: In a Python program, when the classmethod getName() function is executed, it has access to the calling class's bindings i.e. COMPANY_NAME). So:

  • Is something along these lines legal in Java?
  • If so, what's the correct syntax and/or idiom?
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
fearless_fool
  • 33,645
  • 23
  • 135
  • 217
  • Does this help? [Are static methods inherited in Java?](https://stackoverflow.com/questions/10291949/are-static-methods-inherited-in-java) – Unmitigated Aug 12 '20 at 21:22
  • This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) . Do you have a higher level problem you are trying to solve? – Turing85 Aug 12 '20 at 21:23
  • @Turing85: Higher level problem: Yes -- USB devices. Before I have an instance of the USB device, I have static methods that can query the HW. I need configure the HW before I can instantiate the object, thus the static method. For now, I'm passing the `COMPANY_NAME` (or equiv) as a parameter to the config function. Works, but that means I need to create an identical function in each subclass. That feels wrong. – fearless_fool Aug 12 '20 at 21:33
  • Java static methods aren’t really class methods. Using an instance method seems better. Maybe you are reinventing enums? – Nathan Hughes Aug 12 '20 at 21:34

0 Answers0