-1

Following super-class/sub-class relationship:

public abstract class A {
  public Class<? extends A> getSubClass() {
      Class<? extends A> clazz = ???
    }
}

public class B extends A {
  /* some implementation*/
}

public class Foo {
  public static void main(String... args) {
    A a = new B();
    a.getSubClass();
  }
}

Is there a way that b.getSubClass()returns the acutall sub-class type?

Hannes
  • 5,002
  • 8
  • 31
  • 60
  • 1
    Uh...by replacing `???` with `getClass()`? – Kayaman Jul 10 '17 at 20:31
  • @Kayaman I should vote down, my own example was not right, I corrected it - sorry :-( – Hannes Jul 10 '17 at 20:35
  • 2
    It's the same thing. Even though you could just call `a.getClass()`. Is this really your question, or is there something else you're trying to understand? – Kayaman Jul 10 '17 at 20:37
  • @Kayaman Now I am complete confused. I do Java development for years and thought I tested this and it did not work. Strange things happen if days are long. Thanks for your help, anyways! – Hannes Jul 10 '17 at 20:40

1 Answers1

0

This

package test;

public class SubClass {
    public static void main(String[] args) {
        final A b = new B();

        System.out.println("Class: " + b.getSubClass().getName());
    }

    public static abstract class A {
        public Class<? extends A> getSubClass() {
            return this.getClass();
        }
    }

    public static class B extends A {
        // No further implementation
    }
}

produces

Class: test.SubClass$B

Even in super-class methods, the actual class is the sub-class.

Steve11235
  • 2,849
  • 1
  • 17
  • 18