Java self - classes and objects inherit

What is Java's inheritance?

In LOL, the weapon is an article, but also the name and price
so the design category, allowing weapons inherited items, which inherits the name and price of property

Step 1: Item Item type

Item Item class has attributes name, price

public class Item {
    String name;
    int price;
}

Step 2: weapons-grade Weapon (not inherited)

Weapons Class: Weapon not inherit Item wording
independent design name and price properties
at the same time more than one property damage attack

public class Weapon{
    String name;
    int price;
    int damage; //攻击力
 
}

Step 3: weapons-grade Weapon (inherited class Item)

This time Weapon Inheritance Item
although he did not design Weapon name and price, but through inheritance Item class, but also with the name and price properties

public class Weapon extends Item{
    int damage; //攻击力
     
    public static void main(String[] args) {
        Weapon infinityEdge = new Weapon();
        infinityEdge.damage = 65; //damage属性在类Weapon中新设计的
         
        infinityEdge.name = "无尽之刃";//name属性,是从Item中继承来的,就不需要重复设计了
        infinityEdge.price = 3600;
         
    }
     
}

Exercise : Armor
(Armor armor design a class
inherits Item class, and provide an additional attribute ac: Armor Level int type

Examples of the two Armor:
Name Level Price armor
cloth 30015
chainmail 50040)

Code:

public class Armor extends Item{
 
    int ac; //护甲等级
     
    public static void main(String[] args) {
        Armor cloth = new Armor();
        cloth.name="布甲";
        cloth.price=300;
        cloth.ac = 15;
         
        Armor chainMail = new Armor();
        chainMail.name="锁子甲";
        chainMail.price=500;
        chainMail.ac = 40;
    }
     
}

Guess you like

Origin www.cnblogs.com/jeddzd/p/11417789.html