This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Explain how it works so. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Explain how it works so." Watch "Explain how it works so." New topic
Author

Explain how it works so.

James Tharakan
Ranch Hand

Joined: Aug 29, 2008
Posts: 580

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.


SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Sunil Chandurkar
Ranch Hand

Joined: Jan 09, 2008
Posts: 37
James,

Also the mammal object cannot call methods defined in the cattle class.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38036
    
  22
[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]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Explain how it works so.
 
Similar Threads
output
Inheritance doubt
polymorphism
Output........?
explain the flow of the program