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.