I'm doing the following exercise in Thinking in Java 4th Edition by Bruce Eckel:
Exercise 16: (2) Create a class called Amphibian. From this, inherit a class called Frog. Put appropriate methods in the base class. In main(), create a Frog and upcast it to Amphibian and demonstrate that all the methods still work.
What is the difference between Frog f = new Frog();
and Amphibian f = new Frog();
in:
class Amphibian {
void go() { System.out.println("go"); }
void stop() { System.out.println("stop!"); }
}
class Frog extends Amphibian {
void go() { System.out.println("not go"); }
}
public class EFrog {
public static void main(String[] args) {
Frog f = new Frog();
f.go();
}
}
To understand the difference, let's add another method in
Frog
that is not inAmphibian
Now let's take a look at what's the difference :
Bottom line.
Frog
is anAmphibian
soFrog
can do whatever anAmphibian
can.Amphibian
is not aFrog
soAmphibian
can't do everything aFrog
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 sayFrog f = new Frog()
you are programming to an implementation.Now coming to the actual question that the book asks you to try :
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.