Why shouldn't we call a public method from another public?

Someone told me that we should not call the public method of a class from another public method in the same class. Now I can not understand this, since I do not see any problems with this. Once a method is declared public, its contract is fixed for the lifetime and, therefore, there should be no problems when calling it from another public method.

So, I'm not sure if this statement is true or is it okay to call it public api from another public api [Is this from a design point of view]?

+5
source share
6 answers

Is your compiler compiled when you try? No? Then it is legal in this regard.

, "" - , ( , )? ? .

, .

+11

, . , , . , , .

. ,

+6

, , , , . , , , API.

, , java.lang, .

java.lang.String:

1462    public boolean startsWith(String prefix) {
1463        return startsWith(prefix, 0);
1464    }

, .

+4

, . , . - Java , .

, ? , , , .

+2

, , , . . / .

0

-, - . :

public class Parent {

    //return sum
    public double getSum(double... value){
        //implementation
    }

    //return average
    public double getAverage(int count){
        //call getSum
        double sum = getSum(20, 40, 60);
        return sum / count;

    }
}

public class Child extends Parent {

    @Override
    public int getSum(double... obj){
        // change implementation
        // always return 100;
    }
}

If you call the GetApid method of a child object, you will get an unexpected value, the entire interface of the Child object will be violated. You must also override the getAverage method ...

String class example

1462    public boolean startsWith(String prefix) {
1463        return startsWith(prefix, 0);
1464    }

from this point of view, it’s wrong, because the string is final, so you cannot inherit it and override its public methods.

0
source

All Articles