Demonstrate the object-oriented idea in Java. The use of interfaces (abstract classes): breeders feed animals with food.

Source: Internet
Author: User

Package com. softeem. Demo;

/**
* @ Authorleno
* Animal Interfaces
*/
Interface animal
{
Publicvoid eat (Food food );
}
/**
* @ Authorleno
* Animal: Cat
*/
Class cat implements animal
{
Publicvoid eat (Food food)
{
System. Out. println ("kitten" + food. getname ());
}
}
/**
* @ Authorleno
* Animal: Dog
*/
Class dog implements animal
{
Publicvoid eat (Food food)
{
System. Out. println ("Puppy chew" + food. getname ());
}
}

/**
* @ Authorleno
* Abstract Food class
*/
Abstractclass food
{
Protected string name;
Public String getname (){
Returnname;
}

Publicvoid setname (string name ){
This. Name = Name;
}
}

/**
* @ Authorleno
* A type of food: Fish
*/
Class fish extends food
{
Public fish (string name ){
This. Name = Name;
}
}
/**
* @ Authorleno
* A type of food: Bone
*/
Class bone extends food
{
Public bone (string name ){
This. Name = Name;
}
}

/**
* @ Authorleno
* Breeders
*
*/
Class Feeder
{
/**
* The breeder feeds some food to an animal.
* @ Paramanimal
* @ Paramfood
*/
Publicvoid feed (animal, Food food)
{
Animal. Eat (food );
}
}

/**
* @ Authorleno
* Test whether a breeder feeds animals.
*/
Publicclass testfeeder {

Publicstaticvoid main (string [] ARGs ){
Feeder feeder = new feeder ();
Animal animal = new dog ();
Food food = new bone ("meat bone ");
Feeder. Feed (animal, food); // feed the meat to the dog
Animal = new CAT ();
Food = new fish ("fish ");
Feeder. Feed (animal, food); // feed the cat

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.