I am having hard time to understand some principles about overriding and overloading.
public class Figure{
public void stampa(Figure f){
System.out.println("Figure");
}
}
public class Square extends Figure{
public void stampa(Square q){
System.out.println("Square");
}
}
public class Rectangle extends Square{
public void stampa(Rectangle r){
System.out.println("Rectangle");
}
public void stampa(Square r){
System.out.println("Particular Rectangle");
}
public void stampa(Figure f){
System.out.println("Particular Figure");
}
}
public class Test{
public static void main(String args[]){
Figure f1,f2;
Square q = new Rectangle();
Rectangle r = new Rectangle();
f1 = new Square();
f2 = new Rectangle();
f1.stampa(f2); //Figure
q.stampa(r); //Particular Rectangle
f1.stampa(q); //Figure
q.stampa(f1); //Particular Figure
q.stampa(q); //Particupar Rectangle
}
}
I know that public void stampa(Square q)
is overloading public void stampa(Figure f)
and not overrding it.
And public void stampa(Rectangle r)
and public void stampa(Figure f)
are also overloading public void stampa(Square q)
.
Also public void stampa(Square q)
in Rectangle class is overriding the method in Square class.
First question
it's about this result : q.stampa(f1); //Particular Figure
I know that at compile-time q
is an Square
so i will look at this method public void stampa(Square q)
in Square
class. and at run-time q
is Rectangle
so i thought the result might be "Particular Rectangle" instead of "Particular Figure"
Not sure what I'm doing wrong
Second question
If at this moment Rectangle
extends Figure
and not any more Square
, I will certainly have compilation error on Square q = new Rectangle();
what happens to the varibale q
(there will be have such a variable as Square q
or we dont have any varible with name q?) and what will be the result of q.stampa(f1);
Thanks and sorry for my english and please correct me if I'm wrong at some point.
I know that at compile-time
q
is anSquare
so i will look at this methodpublic void stampa(Square q)
in Square class.
You're forgetting that Square
contains two methods: stampa(Square q)
and stampa(Figure f)
. The latter is inherited from Figure
and is selected at compile time as the most only appropriate overload.
and at run-time
q
is Rectangle so i thought the result might be "Particular Rectangle" instead of "Particular Figure"
Overloads are selected at compile time, and overrides at runtime. As stated, stampa(Figure f)
is already selected at compile time. Once it's actually invoked, the runtime sees that q
is an instance of Rectangle
and delegates the invocation to Rectangle.stampa(Figure f)
.
As for the second question, I don't really understand what you're asking. A compile error means the code is invalid and nothing happens. q.stampa(f1)
will never be called and will never return a result.