how to call the method without knowing the name of the class?


I have defined two classes below:

public class junk {
   private BigInteger a = BigIngeger.valueOf(1), b=BigInteger.valueOf(2), c;

   public void DoSomething() {
      c = a.add(b);

   // ... other stuff here

public class junkChild extends junk {
   private BigDecimal a = BigDecimal.valueOf(1), b=BigDecimal.valueOf(2), c;
   // I want a, b, c to override the original BigInteger a,b,c
   // ... other stuff here

public class myClass {
   public static void main(String args[]) {
      junk a1 = new junkChild();

Unfortunately the above does not work.

What I want to do is to simply change a, b, c to BigDecimal in junkChild without rewriting DoSomething() again. Even if I have to write it again, the code will be exactly the same, so there should be a way I can make this work without having to write it. The DoSomething function should check that the type a1 has an add method of the correct input and return type, and if so, invoke it without being worried about what type a, b, c are.

Can this be done?

No, you can't do this - at least not at compile-time. The two add methods are effectively unrelated - they're not from an interface or anything like that.

You could do it with reflection (after adding properties for a, b and c or something similar - fields can't be "overridden" like this), but it wouldn't be terribly nice.