• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding

 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

Please explain me the following lines from K&B page No 103

even if you added an eat()
method to Horse, it wouldn't be an override of Animal's eat() method.

public class TestAnimals {
public static void main (String [] args) {
Horse h = new Horse();
h.eat(); // Not legal because Horse didn't inherit eat()
}
}
class Animal {
private void eat() {
System.out.println("Generic Animal Eating Generically");
}
}
class Horse extends Animal { }

Why it is not overriding when we add aeat method to horse class???

Thanks in advance
Suma
 
Santhosh Kumar
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because 'Animal.eat' method is declared as 'private' class making it visible only inside the 'Animal' class. When you add a eat method to 'Horse' class, it becomes a new method inside 'Horse' class and hence not overriding.
 
Mamadou Touré
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sumaraghavi,

remember this : Only inherited methods can be overriden. So as private methods can never been inherited, so they're not overriden

hope this will help
 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic