Java继承_概念与实现(一)

来源:互联网 发布:淘宝开通企业店铺 编辑:程序博客网 时间:2024/06/07 03:25

        继承就是子类继承父类行为,表明子类是一种特殊的父类,并且具有父类所不具有的一些属性或方法。

        概念不容易理解,举个大家都熟悉的魔兽游戏例子,加深一下理解继承。

         通过上面的图,我们知道,游戏中有很多对象,会动的生物和不会动的建筑,会动的生物有英雄、自己造的兵。

         我们知道所有的对象都有一个生命值,当生命值为零的时候,游戏对象就被删除了,那我们可以在游戏对象中设定一个属性,生命值和两个方法,生命增加和生命减少。

         生物是能够移动的游戏对象,所以,生物可以继承于游戏对象。生物又有一些游戏对象不具有的属性和方法。作为游戏中的生物,都有名称和攻击的属性,例如一个生物是小鱼人,一个生物是大海龟,当然也可以是大法师或者山丘这样的英雄。另外生物都会移动和普通攻击,我们可以给生物增加这两个方法。

         英雄除了生物的一般属性,我们还知道英雄是有名字和技能,这样,我们可以建一个英雄的类,继承生物。

         总而言之,继承就是子类继承父类的特征和行为,使得子类具有父类的各种属性和方法。或子类从父类继承方法,使得子类具有父类相同的行为。

Java继承的方法:

         使用extends关键字。

继承的代码:

package com.ws.basic;class GameObject{int life;public GameObject(int life) {super();this.life = life;}public int life_reduce(int ai_reduce){life = life - ai_reduce;return life;}public int life_add(int ai_add){life = life + ai_add;return life;}}class Creature extends GameObject {String mc;int attack;public Creature(String mc, int attack,int life) {super(life);this.mc = mc;this.attack = attack;}public void move() {System.out.println(mc+"在移动!");}public void normal_attack() {System.out.println(mc+"在普通攻击!");}}class Hero extends Creature{String name;String skill;public Hero(String name,String skill,String mc, int attack,int life) {super(mc,attack,life);this.name = name;this.skill = skill;}public void skill_attack(){System.out.println(mc + name + "用"+skill+"攻击!");}public void eat_food(int food){life_add(food);System.out.println(mc + name + "吃了"+food + "血,当前血量"+life);}}public class testjc {  public static void main(String[] args) {   Hero heroDfs = new Hero("甘道夫","暴风雪","大法师",14,450);  Creature fishman=new Creature("小鱼人",5,200); Creature turtle=new Creature("大海龟",20,2000);  heroDfs.skill_attack();  fishman.life_reduce(10); System.out.println(fishman.mc + "当前血量"+fishman.life); turtle.life_reduce(20); System.out.println(turtle.mc + "当前血量"+turtle.life);  turtle.normal_attack(); fishman.normal_attack(); heroDfs.life_reduce(5); System.out.println(heroDfs.name + "当前血量"+heroDfs.life); heroDfs.life_reduce(5); System.out.println(heroDfs.name + "当前血量"+heroDfs.life);    }}

执行的结果:

大法师甘道夫用暴风雪攻击!小鱼人当前血量190大海龟当前血量1980大海龟在普通攻击!小鱼人在普通攻击!甘道夫当前血量445甘道夫当前血量440

        测试模拟了大法师甘道夫用暴风雪攻击小鱼人和大海龟,小鱼人和大海龟反击大法师的行为。oo设计最适合使用的地方就是游戏,定义好类,就可以实例化游戏对象,而继承将大大的减少代码量。


0 0
原创粉丝点击