0

what is the difference between the following two objects. Both will print "I am tuna". My point here is I have difficulty to understand the difference between the 'food' data type and 'tuna' data type. Any help will be greatly appreciated. Thanks!

class food {
   public void talk(){System.out.println("I am food");
   }
}

class tuna extends food {
   public void talk(){System.out.println("I am tuna");
   }
}

class runThisProgram{
   public static void main(String[] args){

      food f = new tuna();
      tuna t = new tuna();

      f.talk()
      t.talk()
   }
}
Sylvain
  • 553
  • 3
  • 14
  • 26
  • http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface – Sotirios Delimanolis Nov 22 '16 at 00:09
  • 1
    It works like in real life. If you ask me "give me some food", I might give you an apple, a cheese, or a piece of tuna. All those things are food. If I choose to give you tuna, it will taste and smell like tuna. But that doesn't mean I can't refer to tuna as "food". Your variable is of type food, but it refers to an object that is a tuna. Since tuna is food, that is not a problem. – JB Nizet Nov 22 '16 at 00:10
  • for your first method call, f.talk(), Only reference is of your parent class but the object you are creating is of derived class, hence in case of f.talk() as well it will call method from Tuna (derived) class. – Coder Nov 22 '16 at 06:05

0 Answers0