How to call a method without knowing the class name?

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();
      a1.DoSomething();
   }
}

Unfortunately this does not work.

I just want to change a, b, con BigDecimalin junkChildwithout overwriting DoSomething()again. Even if I have to write it again, the code will be exactly the same, so there must be a way I can do this work without writing it. The function DoSomethingshould check that the type of a1a method of addthe correct type of input and return, and if so, call him, without worrying about what type a, b, care located.

Can this be done?

+3
source share
4

, - , . add - - .

( a, b c - - "" ), .

+4

, , , Java . .

+2

, Java " ", . BigDecimal BigInteger Number, add() , .

I think you need to clearly indicate that you are working in the parameters of the doSomething () method. Then you can override doSomething () to work with both types:

public BigDecimal doSomething(BigDecimal a, BigDecimal b) {
        return a.add( b );
}

public BigInteger doSomething(BigInteger a, BigInteger b) {
    BigDecimal x = new BigDecimal(a);
    BigDecimal y = new BigDecimal(b);
    BigDecimal z = doSomething(x, y);
    return z.toBigInteger();
}

The second method is just a conversion method, which then calls the real logic in the first method.

+2
source

since Number (the closest ancestor of both classes has no add method), you can first convert BigInteger to BigDecimal:

new BigDecimal(bi)
+1
source

Source: https://habr.com/ru/post/1727248/


All Articles