【发布时间】:2021-11-24 21:13:03
【问题描述】:
我的帖子已被关闭,因为另一个问题的重复并不能真正解决我的问题,所以我再次发布它。因为它不是关于比较字符串,而是关于将一个对象的字符串传递给另一个对象。
我试图通过编写一个代码来练习 Java 的继承,该代码由称为 Person 的父类组成,该类有两个子类 SuperPerson 和 Civil ,以及 SuperPerson 类,它有两个子类,分别称为 Hero 和 Villian。 我试图实现一个名为 Protect 的方法,该方法仅供 Hero 类使用,该类只能在 Civil 类作为目标。 所以,当我运行代码时,这里的主要问题是,在另一个英雄试图保护一个已经受到另一个英雄保护的平民的情况下,以及一个恶棍试图攻击平民的情况下,它不会显示保护者的名字谁在英雄的保护之下。
主要方法:
Hero h1 = new Hero("Spiderman", 25,"Male", "Web");
Hero h2 = new Hero("Batman", 35, "Male","Wealth");
SuperPerson v1 = new Villian("Goblin", 47,"Male", "Goblin Power");
Person c3 = new Civil("Mary", 24,"Female");
h1.protect(c3); //First Hero object protecting the Civil object
h2.protect(c3);//Different Hero object trying to protect the same Civil object
v1.attack(c3);//Villian attacking civil under protection
输出:
Mary is under Spiderman's proction.
Mary is already under null's protection //Bug here
The target is under null's protection //Bug here
(Person)父类:
public class Person {
boolean protection;
}
(SuperPerson)父类:
public class SuperPerson extends Person {
String protector;
}
第一个拥有protect方法的子(Hero)类:
public class Hero extends SuperPerson {
void protect(Person target) {
if(target.type.equals("Super Villian")) {
System.out.println("You can not protect a villian!");
}
else {
if(target.health != 0) {
if(target.protection == false) {//to protect
target.protection = true;
this.protector = this.name;
System.out.println(target.name + " is under " + this.protector + "'s proction.");
}
else {
if(this.protector != this.name) {//under someone else protection so can not unprotect
System.out.println(target.name + " is already under " + protector + "'s protection");//Bug here
}
else {//to unprotect
target.protection = false;
System.out.println(target.name + " is no longer under " + this.name + "'s protection");
}
}
}
else {
System.out.println("Target is already dead.");
}
}
}
}
另一个孩子(Villian)类:
public class Villian extends SuperPerson{
int attack(Person target) {
if(target.type.equals(this.type)) {
System.out.println("Invalid target!");
return 0 ;
}
else {
if(target.protection == true) {
System.out.println("The target is under " + protector + "'s protection"); //Bug here
return 0;
}
else {
return super.attack(target);
}
}
}
}
【问题讨论】:
-
此类问题如果包含minimal reproducible example,则更有可能得到解决。
标签: java string inheritance null super