Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Explain how it works so.

 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Mammal
{
void eat(Mammal m)
{
System.out.println("Mammal eats food");
}
}
class Cattle extends Mammal
{
void eatg(Cattle c )
{
System.out.println("Cattle eats hay");
}
}

public class Simply
{
public static void main(String[] args)
{
Mammal m= new Mammal();
Cattle c = new Cattle();

m.eat(c);
}
}



Output is :- Mammal eats food

I am sending base class object as argument.
But the super class is EXPECTING its own class's object.

Can anyone explain.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by James Tharakan:
...I am sending base class object as argument.
But the super class is EXPECTING its own class's object...

That works because of method invocation conversion.

An instance of Cattle IS-A Mammal, so when you call the eat method using a Cattle reference, the reference is automatically upcast (converted) to type Mammal.
 
Sunil Chandurkar
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James,

Also the mammal object cannot call methods defined in the cattle class.
 
Campbell Ritchie
Sheriff
Posts: 48404
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Moderator's hat on]
I trust you have got a satisfactory reply, but please look at these two FAQs which will make future postings easier to read and more likely to attract answers.
1. 2.
[Moderator's hat off]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic