简体   繁体   中英

If generics are computed as compile time, why doesn't this work?

Say I have 2 classes like this:

public class Circle {
  private int area;

  public Circle(int a) {
    area = a;
  }

  public int getArea() {
    System.out.println("Circle::getArea");
    return area;
  }
}

public class Square {
  private int area;

  public Square(int a) {
    area = a;
  }

  public int getArea() {
    System.out.println("Square::getArea");
    return area;
  }
}

I'd like to write something like

  public static <T> int genericArea(T shape) {
    return shape.getArea();
  }

But that fails with error: cannot find symbol

It was my understanding that because generics are solved at compile time it should be able to verify that all usages of that method are with Square or Circle class.

fiddle here: https://repl.it/repls/InnocentDarkmagentaDifferences

Note that I know how I would do it with interfaces, but: 1. I'm curious 2. In the specific problem I'm trying to solve, I cannot modify Circle and Square because they are auto-generated by some other system

C++ uses templates ; it creates a separate copy (originally, in generated source code) of genericArea for each use. That means that you can use any type that has getArea() for it.

Java uses generics instead; there is only one copy of the genericArea method, and it can handle anything that matches its type parameter. But your type parameter is essentially just Object since you haven't limited it to something like T extends HasArea , and there's no Object.getArea() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM