Java self-learning-interface and inheritance rewriting

Keywords: Java

Java rewriting method

Subclasses can inherit object methods of parent classes

Repeated provision of this method after inheritance is called method rewriting

Also known as Override Override

Step 1: The parent class Item

The parent class Item has a method called effect

package property;
 
public class Item {
    String name;
    int price;
 
    public void buy(){
        System.out.println("purchase");
    }
    public void effect() {
        System.out.println("After use, it can be effective.");
    }
 
}

Step 2: Subclass LifePotion

Subclass LifePotion inherits Item and also provides method effect

package property;
 
public class LifePotion extends Item{
     
    public void effect(){
        System.out.println("After using the blood bottle, the blood can be returned.");
    }
     
}

Step 3: Call the overridden method

Call the overridden method
Calls will execute overridden methods, not methods from the parent class
So the effect of LifePotion prints:
"After using the blood bottle, the blood can be returned."

package property;
 
public class Item {
    String name;
    int price;
     
    public void effect(){
        System.out.println("After use, it can be effective.");
    }
     
    public static void main(String[] args) {
        Item i = new Item();
        i.effect();
         
        LifePotion lp =new LifePotion();
        lp.effect();
    }
     
}

Step 4: What if there is no such mechanism to rewrite?

Without such a mechanism, that is, LifePotion class, once Item is inherited, all methods cannot be modified.

But LifePotion also wants to provide a little different functionality. To achieve this goal, it can only abandon inheriting Item, rewrite all attributes and methods, and then make minor changes when writing effect s.

This increases development time and maintenance costs.

package property;
 
public class Item {
    String name;
    int price;
 
    public void buy(){
        System.out.println("purchase");
    }
    public void effect() {
        System.out.println("After use, it can be effective.");
    }
 
}

package property;
 
public class LifePotion {
    String name;
    int price;
 
    public void buy(){
        System.out.println("purchase");
    }
    public void effect(){
        System.out.println("After using the blood bottle, the blood can be returned.");
    }
}

Practice: Rewrite
(Design a MagicPotion-like blue bottle, inherit Item, rewrite the effect method
And output "Blue Bottle can return to magic after use")

Answer:

package property;
 
public class MagicPotion extends Item{
 
    public void effect(){
        System.out.println("When the blue bottle is used, it can return to magic.");
    }
}

Posted by silverglade on Thu, 03 Oct 2019 17:41:42 -0700