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