How to change member function signature for derived class in Java

First, I am expanding the existing class structure and cannot change the original with this warning:

I would like to do this:

class a
{
   int val;

   ... // usual constructor, etc...

   public int displayAlteredValue(int inp)
   {
     return (val*inp);
   }
}

class b extends a
{
   ... // usual constructor, etc...

   public in displayAlteredValue(int inp1, int inp2)
   {
     return (val*inp1*inp2);
   }
}

As I said, I cannot change class a, and I want to save the name of the function displayAlteredValueinstead of creating a new function. If this can be done, I need to change multiple instances ato instances b. I do not want to spend a lot of time replacing many function calls with displayAlteredValue. (And yes, I understand that there are things like search and replace, but for other reasons, as this will be problematic).

Any ideas?

+3
source share
7 answers

. , , . , .

public class DerivedOverload {

    /**
     * @param args
     */
    public static void main(String[] args) {
        A classA = new A(); 

        B classB = new B();

        System.out.println("DerivedOverload.main() classA.displayAlteredValue(2) : " + classA.displayAlteredValue(2));

        System.out.println("DerivedOverload.main() classA.displayAlteredValue(2) : " + classB.displayAlteredValue(2,2));
    }



}


class A
{
   int val = 2;

   A(){

   }

   public int displayAlteredValue(int inp)
   {
     return (val*inp);
   }
}

class B extends A
{
   B(){

   }

   public int displayAlteredValue(int inp1, int inp2)
   {
     return (val*inp1*inp2);
   }
}

. DerivedOverload.main() classA.displayAlteredValue(2): 4 DerivedOverload.main() classA.displayAlteredValue(2): 8

+3

, . b, , .

, , , , - b, a, , b.

:

// this works because b is a subclass of a
a anObject = new b();

// this will not compile because the declared type of anObject is a
int x = anObject.getValue( 1, 2 );

b, b, .

+2

,

public int displayAlteredValue(int inp)
{
  return super.displayAlteredValue(inp);
}
+1

, , . . , , , ? b.displayAlteredValue ? , ( ), Liskov.

, .

- , , .

+1

, .

b . a. 2-arg b.

a 1-arg, , .

+1

B :

public int displayAlteredValue(int inp) 
{
    return -1;
}

, -1 . int , , null, .

0
source

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


All Articles