Dark Horse Day11 Decoration class

Source: Internet
Author: User

If you want to fix a method in a class there are three ways to do it: inherit, write a decoration class, dynamic agent

Here I mainly introduce the decoration class:

1. Write a interface Animal

Package com.itheima.pool;
Public interface Animal {
public void eat ();
public void bite ();
}

2. Write a dog class that inherits the animal interface:

Package com.itheima.pool;
public class Dog implements animal{
public void Eat () {
System.out.println ("Dog is eatting ...");
}
public void bite () {
System.out.println ("Dog is bitting ...");
}
}

3. Write a decorative class Decoratedog class also inherits the same interface as the dog:

A constructor is provided in this class, with a animal interface parameter, in order to pass in the dog object at New Decoratedog .... Corresponds to Polymorphic

Package com.itheima.pool;
public class Decoratedog implements animal{
Private Animal Ani=null;
Public Decoratedog (Animal ani) {
This.ani=ani;
}
@Override
public void Eat () {
Ani.eat ();
}
@Override
public void bite () {
System.out.println ("Dog is Mie mie ....");
}
}

4. Write a test class Dogtest

Package com.itheima.pool;
public class Dogtest {
public static void Main (string[] args) {
Dog dog= New Dog ();
Animal ani=new Decoratedog (dog);
Ani.bite ();
}
}

5. Operational results:


The results are running Mie mie ... This is because the method that was modified in the adornment class was called.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dark Horse Day11 Decoration class

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.