I have a code and I am not able to get why the output will be "Radial Tire with long".Can somebody help me to understand this code?
class Tyre {
public void front() throws RuntimeException {
System.out.println("Tire");
}
public void front(long a) {
System.out.println("Radial Tire with long");
}
}
class TestSolution extends Tyre {
public void front() {
System.out.println("Radial Tire");
}
public void front(int a) throws RuntimeException {
System.out.println("Radial Tire with int");
}
public static void main(String... args) {
Tyre t = new TestSolution();
int a = 10;
t.front(a);
}
}
front
is not overridden inTestSolution
, it is overloaded.You can regard an overloaded function as a completely different function, like one with a different name.
So
t.front(a)
will call the one inTyre
, with ana
implicitly converted tolong
.General rule: if I have a variable of one class I can access only methods and components defined in that class.
The only particular case is:
In these cases you can follow the following rule:
In your case as stated before the method is not overridden so you can't apply the last rule.
So if we go with definitions
Overloading means methods with same name but with different number or order of parameters.
Overriding means method with same name with same number of parameters along with rules mentioned here
So in your case
front
method is overloaded in both the classesTyre
andTestSolution
method
front()
fromTyre
class is overridden in classTestSolution
.no overriding in case of method
front(long a)
andfront(int a)
.There's no overriding taking place in your
main
.t
's static (compile-time) type isTyre
, so, since method overload resolution is determined by the compile-time type of the instance, the onlyfront
methods available for the compiler to choose from are those declared in the base classTyre
:Only the latter (
public void front(long a)
) matches the arguments of the callt.front(a)
, and that method is not overridden by the sub-class. ThereforeRadial Tire with long
is displayed.Calling
((TestSolution)t).front(a);
would invoke the sub-class's method -public void front(int a)
.Lets understand the difference between overloading and overriding
Overloading:
Overriding:
Tyre
declaredfront()
method withlong
as parameter.TyreSolution
declaredfront()
method withint
as parameter.Since the method signature is different,
TyreSolution
overloadsTyre
'sfront()
methodIf you change signature of
front()
inTyreSolution
to acceptlong
value as input parameter instead ofint
, thenTyreSolution
overridesTyre's
front()
method.e.g.
TestSolution
class definition offront()
methodoutput: