JAVA-Interface and Inheritance (3) Rewriting

Parent 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("购买了" + name);
	}
	public void effect() {
    
    
		System.out.println("购买后的效果");
	}
}

Subclass LifePotion

The subclass LifePotion inherits Item and also provides the method effect

package property;

public class lifepotion extends item{
    
    
	public void effect() {
    
    
		System.out.println("使用血瓶可以回血");
	}
	public static void main(String args[]) {
    
    
		lifepotion b = new lifepotion();
		b.effect();
	}
}

Whose object calls effect will print whose method

What if there is no rewriting mechanism like this?

If there is no overriding mechanism, that is to say, the LifePotion class, once it inherits Item, all methods cannot be modified.

But LifePotion hopes to provide a little different function. In order to achieve this goal, we can only give up inheriting Item, rewrite all the properties and methods, and then make a little change when writing the effect.

This increases development time and maintenance costs

Exercise-Rewrite ⭐⭐

Design a class MagicPotion blue bottle, inherit Item, rewrite the effect method,
and output "After the blue bottle is used, you can return to magic"

package property;

public class magicpotion extends item{
    
    
	public void effect() {
    
    
		System.out.println("使用蓝瓶后恢复蓝量");
	}
	public static void main(String args[]) {
    
    
		magicpotion a  = new magicpotion();
		a.effect();
	}
}

Guess you like

Origin blog.csdn.net/qq_17802895/article/details/108511598