Calling An Inherited Class Method From Java

2019-07-29 14:47发布

问题:

In Python, class methods can be inherited. e.g.

>>> class A:
...  @classmethod
...  def main(cls):
...   return cls()
...
>>> class B(A): pass
...
>>> b=B.main()
>>> b
<__main__.B instance at 0x00A6FA58>

How would you do the equivalent in Java? I currently have:

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");
    }
}

I'd like to call B.main() and have it print "B", but clearly it will print "A" instead, since "new A()" is hardcoded.

How would you change "new A()" so that it's parameterized to use the class it's in when called, and not the hard-coded class A?

回答1:

Static methods in java are not classmethods they are staticmethods. In general it is not possible to know which class reference the static method was called from.



回答2:

Your class B does not have a main method and static methods are not inherited.



回答3:

The only way I can see this happening is to find whatever is calling A.main( String[] arg ) and change it to call B.main instead.

B.main:

   public static void main( String[] arg ) {
        new B().run();
    }

How is your program started? Is there a batch file, shortcut, etc? Something you can change? Where does A.main get called?



回答4:

I think this isn't possible. Here's why:

In Java, the implementation of a method is determined by the instance's run-time type. So, to execute B.show(), you need to have an instance of B. The only way I could see to do this, if the method that constructs the instance is supposed to be inherited, is to use Class.newInstance() to construct an instance of a type that's not known at runtime.

The problem with that is that within a static method, you have no reference to the containing class, so you don't know whose newInstance method to call.

Why do you want to do this, though? There may be some better way to achieve whatever it is you want to achieve.



回答5:

In your example I wouldn't put your main method inside of A. This is setup as the entry point into the system (you can't be in B if you are specifically entering into A).

In the example below I created class A, B, and C. Class C instantiates A and B and runs them. Notice that in C I created an A, a B, and another A that I instantiate as a B. My output is: A B B

Hopefully this makes sense.

public class A { 
public void show(){ 
    System.out.println("A"); 
  } 

public void run(){ 
    show(); 
  }  
} 

public class B extends A { 
 @Override 
 public void show(){ 
    System.out.println("B"); 
    } 
 } 

public class C {
public static void main(String[] args) {
    A a = new A();
    B b = new B();
    A anothera = new B();

    a.show();
    b.show();
    anothera.show();
   }
}