But I don't understand What is the difference between Frog f = new Frog(); and Amphibian f = new Frog();
To understand the difference, let's add another method in Frog
that is not in Amphibian
class Frog extends Amphibian {
void go() { System.out.println("not go"); }
void come() { System.out.println("come"); }
}
Now let's take a look at what's the difference :
public class EFrog {
public static void main(String[] args) {
Frog f = new Frog();
f.go();
f.come();
Amphibian a = f;
a.come();//this won't compile
}
}
Bottom line. Frog
is an Amphibian
so Frog
can do whatever an Amphibian
can. Amphibian
is not a Frog
so Amphibian
can't do everything a Frog
can.
When you say Amphibian a = new Frog()
, you are programming to an interface (not the java interface but the general meaning of interface). When you say Frog f = new Frog()
you are programming to an implementation.
Now coming to the actual question that the book asks you to try :
In main( ), create a Frog and upcast it to Amphibian and demonstrate
that all the methods still work.
public class EFrog {
public static void main(String[] args) {
Frog f = new Frog();
Amphibian g = (Amphibian)f;//this is an upcast
g.go(); //okay since Amphibian can go
g.come();//not okay since Amphibian can't come
}
}
I don't think you meant to ask What's the use of upcasting but since the title has already been edited by someone else, why not answer that as well? Upcasting is useful in certain situations such as calling specialized forms of an overloaded methods explicitly. See this answer for additional details.