Saud Saud - 1 year ago 66
Java Question

Why is it a good practice to define a variable with a supertype?

"Introduction to Java programming", says:

To enable generic programming,
it is a good practice to define a variable with a supertype, which can accept a value of any subtype.

Code example:

Object myObject = new Circle();

... // Some lines of code

System.out.println("The circle diameter is " +
((Circle)myObject) .getDiameter());

... // Some lines of code

Why not define myObject as a Circle type in the first place?

Answer Source

Lets make a simple Example with a class Fruit

public class Fruit {
   public void eat() {
       //some code

And two other classes

public class Banana extends Fruit{

public class Apple extends Fruit{


Now let´s create a Person

public class Person {
    public void eat(Fruit f) {;

Let´s use this now

public static void main(String[] args) {
    Person p = new Person();
    // We are creating a random Fruit, and pass it to the person to eat.
    // We can´t be more specific here and don´t need to be more specific
    Fruit f = getRandomFruit();;

public static Fruit getRandomFruit() {
    if(new Random().nextInt(2) == 0) {
        return new Banana();
    } else {
        return new Apple();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download