To understand the result, you need to break down the calculation into four parts.
int r = obj1.metodoX() + obj2.metodoX() + obj2.metodoX(5) +
obj3.metodoX(10, 100);
Part 1: obj1.metodoX()
obj1 matches the ClassA class. Running the method X () returns the value 10 .
Part 2: obj2.metodoX()
The obj2 corresponds to ClasseB . Although obj2 inherits the ClassA methods, the execution of methodX () is that of ClassB , so the value returned is 100 .
3rd Party: obj2.metodoX(5)
This call executes the classB (int n) of ClassB , which in turn returns the result of the expression metodoX() + n
. The method (x) that is called in this expression is that of ClassB , which returns a value of 100, that is, the result of this execution is% which is 500 .
4th Part: 100 * 5
In the above call another method of the ClassB method that calls the methods of ClassB is executed, returning 1100 / strong>.
In this way, the final result is 10 + 100 + 500 + 1100 = 1710 .
On the issue of inheritance, note that there are ClasseA methods with the same name in ClasseB .
In this example found by you, ClassB inherits methods from ClassA , but methods of ClassA were not used in classB < strong>. For this reason, all calls in ClassB refer to the methods themselves and not to those of the parent class.
In order for a ClassB method to call a ClassA method in ClassB , the call should be preceded by the super pointer.
A brief example would be:
public classe ClasseB extends ClasseA {
public int metodoX(){
return 100
}
public int metodoX(int n){
return super.metodoX() * n
}
public int metodoX(int m, int n){
return super.metodoX(m) + metodoX()
}
}
With the example above, the inheritance would be effectively used in the code, so the end result would be different.
For overloading, this was used when classes were implemented with methods of the same name, but with different signatures.