-2
public class Base {
    public static void main(String[] args) {
        Base b = new Derived();
        b.printName();
    }
    public void printName() {
        System.out.println(this.getClass());
    }

}

class Derived extends Base {

}

the code above prints the derived class name. how can I make it print the base class name. Keep in mind that the code is used to classify the question. I don't actually need to print the class name. I need the this in printName be exactly the type of Base even in a Derived instance. It's has not be the name this, anything do the work would be OK. Is it possible?

To further specify the question. Some third party library I used in base class didn't get their job done in Derived class instance. And I figure it out that's because they called getClass() of the this I passed in but didn't get the Class<?> they expected. How can I workaround this?

blah
  • 31
  • 4
  • Why don't you just ask for `instanceof Base`? Although in general that indicates a wonky design to begin with. Also, funky to ask for a child class in the super class unless it's specifically a factory (or just a test, which is probably the case this time). – Dave Newton Oct 19 '15 at 14:57
  • Are you aware of the fact that the root class is always `Object`? So from `Derived`'s perspective, how would you specify when to stop climbing up the inheritance chain? – Siguza Oct 19 '15 at 14:59
  • @singhakash OP wants it to be a `Derived`, but reported as a `Base`. – Dave Newton Oct 19 '15 at 14:59

2 Answers2

2

I think the only thing you can do is

System.out.println(Base.class);

Some GUIs might even auto-rename those when renaming the Base class.

stox
  • 91
  • 1
  • 3
  • 1
    And by "GUI" you mean "IDE"? – Siguza Oct 19 '15 at 15:04
  • 2
    Sure. And while you're at it, mark the `printName()` method as `final` to keep subclasses from overriding it. – Erick G. Hagstrom Oct 19 '15 at 15:08
  • I can't do this. Some third party library I used in base class didn't get their job done in Derived class instance. And I figure it out that because they called getClass() and didn't receive the Class they expected. – blah Oct 19 '15 at 15:14
0

It is not possible, since Java methods are always virtual (those you can override, that is).

See also: Are all method in java implictly virtual

Community
  • 1
  • 1
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43