I’m new to Java, and I’ve read over some tutorials on overriding methods, but an example I’m looking at isn’t working the way I expect. For example, I have the code:
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
public static void main( String[] arg ) {
new A().run();
}
}
public class B extends A{
@Override
public void show(){
System.out.println("B");
}
}
When I instantiate and call B.run(), I would expect to see “B” outputted. However, I see “A” instead. What am I doing wrong?
Edit: Yes, the classes are in two separate files. They’re shown together for brevity.
Edit: I’m not sure how B is being instantiated, as it’s being done by a third-party program using a classloader.
Edit: More info on the third-party program. It starts by calling A.main(), which I didn’t initially show (sorry). I’m assuming I need to make “new A().run();” more generic to use the name of the current class. Is that possible?
That code will output
Bif you:Whatever the problem is, it’s not in the code you’ve quoted.
Updated (after your edit)
If the third-party program is calling
A.main(), there’s nothing (reasonable) you can do inBthat will inject itself intoA. As long asA.mainis doingnew A().run(), it’s going to have an instance ofA, not an instance ofB. There’s no “current class name” to use, or if there is (depends on your point of view), it’sA, notB.You’ll have to get the third-party program to call
Bin some way, rather thanA, or just modifyAdirectly (e.g., getting rid ofBentirely). You do not want to modifyAto make it useB; that tightly binds it to a descendant and makes the separation between them largely pointless.Hope that helps.