简体   繁体   English

如何在Java中存储在多态数组中的对象上调用方法?

[英]How can I call a method on an object that is stored in a polymorphic array in Java?

Hi and thanks for taking time to look at my problem. 您好,感谢您抽出宝贵时间来查看我的问题。

I am trying to call a method on an object held in an object array. 我试图在对象数组中保存的对象上调用方法。

There are three classes: Cards, Guard and Deck. 共有三类:纸牌,守卫和甲板。

The Guard class extends the Cards class. Guard类扩展了Cards类。

The array is of type 'Cards' and is instantiated in the Deck class. 该数组的类型为Cards,并在Deck类中实例化。

The Cards class is pretty much empty: Cards类几乎是空的:

public class Cards  {
}

The object being stored in the array is of type Guard. 存储在数组中的对象的类型为Guard。 Here is the Guard class and it's state and methods: 这是Guard类,它是状态和方法:

public class Guard extends Cards{

    private int cardScore = 2;
    private String cardName = "Guard";
    private String cardAbility = "this is the guard's ability";

    public void printGuardInfo()
    {
        System.out.println("This card score fo the guard is:      "+cardScore);
        System.out.println("The card name is: "+ cardName);
        System.out.println("The card ability is" + cardAbility);
    }
}

I am instantiating the array in the Deck class. 我正在Deck类中实例化数组。 I am then filling a array of type Cards with objects of type Guard.This is polymorphism, I believe. 然后我用Guard类型的对象填充Card类型的数组。我相信这是多态的。

This works and I can print the reference variables held at each index point. 这行得通,我可以打印每个索引点上保存的参考变量。

public class Deck {
    Cards[] deck = new Cards[16];

    public Cards[] getDeck() {
        return deck;
    }

    public void addGuards()
    {
        for(int i=0; i<5; i++)
        {
            deck[i] = new Guard();
            deck[i].printGuardInfo();// Error: cannot resolve method     printGuardInfo()
        }
    }  
}

My problem is that I now cannot call the printGuardInfo() method on deck[i]. 我的问题是我现在无法在deck [i]上调用printGuardInfo()方法。

I have searched and googled for a while now but with no success. 我已经搜索和搜索了一段时间,但没有成功。 I feel like I need an interface, or abstract class of some sort. 我觉得我需要一个接口或某种抽象类。 Unfortunately I am not knowledgeable enough in these areas. 不幸的是,我在这些领域知识不足。

Any help at all is much appreciated, Thank you. 非常感谢您的任何帮助,谢谢。

I´d promote something like this: 我会宣传以下内容:

Make Cards an interface 使Cards成为interface

public interface Cards  {
    void print();
}

Make Guard implement this interface and override the print method there with the needed information. 使Guard实现此接口,并在其中使用所需信息覆盖print方法。

public class Guard implements Cards{
    // ... Other methods and stuff
    @Override
    public void print() {
        System.out.println("This card score fo the guard is:      "+cardScore);
        System.out.println("The card name is: "+ cardName);
        System.out.println("The card ability is" + cardAbility);
    }
    // ... Other methods and stuff
}

Now in the loop you just have to call 现在在循环中,您只需要调用

deck[i].print();

What is getting printed now will be depending on the actual implementation of what has to be printed, but in generall the class Cards will know that it can print now. 现在要打印的内容将取决于必须打印的内容的实际实现方式,但是一般来说, Cards类会知道它现在可以print

Edit: Following @chrylis comment, your class should be called Card instead of Cards . 编辑:在@chrylis评论之后,您的班级应称为Card而不是Cards The reason here? 原因在这里吗? It´s like a simple plan for a single type of Card (class here), but doesn´t represent multiple Cards (multiple cards would be instances of Card ). 这就像是针对单一类型Card的简单计划(此处为类),但并不表示多个Cards (多个Card将是Card实例)。

While some of the proposed solutions make sense in the narrow case (using a combination of instanceof and casting the impacted Cards element to Guard in order to invoke printGuardInfo ), there might be a broader problem with the design of your inheritance. 尽管某些建议的解决方案在狭窄的情况下是有意义的(结合使用instanceof和将受影响的Cards元素强制转换为Guard以便调用printGuardInfo ),但是继承的设计可能存在更广泛的问题。

Assuming Cards is not really an empty class (otherwise the hierarchy does really not produce any benefit), my advice is to group your card objects under a common interface or abstract class (say, Card ), and have that interface provide an abstraction for general methods such as printInfo , which is then implemented by each Card type (you'd get the printGuardInfo code inside the Guard implementation there). 假设Cards不是一个真正的空类(否则该层次结构实际上不会产生任何好处),我的建议是将您的card对象分组到一个通用接口或抽象类(例如Card )下,并让该接口为通用提供抽象方法,例如printInfo ,然后由每种Card类型实现(您将在其中的Guard实现中获取printGuardInfo代码)。

In turn, when iterating your array, you'd invoke printInfo on each card, knowing that each and every child of Card has its own printInfo implementation, without the need to cast or use instanceof . 反过来,在迭代数组时,您知道每个Card子级都有其自己的printInfo实现,而无需printInfo转换或使用instanceofprintInfo在每个printInfo上调用printInfo

您需要将Card投掷给Guard

((Guard) deck[i]).printGuardInfo();

The easiest, most object-oriented way to do this is to change printGuardInfo to toString : 最简单,最面向对象的方法是将printGuardInfo更改为toString

public String toString()
{
    return new StringBuilder("This card score fo the guard is:      ")
                  .append(cardScore).append('\n')
                  .append("The card name is: ")
                  .append(cardName).append('\n')
                  .append("The card ability is ")
                  .append(cardAbility)
                  .toString();
}

You can then call String guardInfo = deck[i].toString(); 然后,您可以调用String guardInfo = deck[i].toString(); to get the guard info and write it to standard output, a logger, etc. 获取警卫信息并将其写入标准输出,记录器等

public String toString() is inherited from Object , so no casting is needed to call it. public String toString()继承自Object ,因此无需强制转换即可调用它。

R2-D2 is right, but if you want to be more 'polymorphic' you should do something like This R2-D2是正确的,但是如果您想更“多态”,则应该执行以下操作

public interface ICard {
    public void printInfo();

}

public class Card implements ICard{

  public void printInfo(
    System.out.println("Card Info");
  }
}

public class Guard extends Card {

   public void printInfo{
        System.out.println("GUARD Info");
 }
}


public vlass Deck{
...
public void addGuards()
{
        for(int i=0; i<5; i++)
        {
          deck[i] = new Guard();
          deck[i].printInfo();
        }
    }  

}

Or even use an abstract class 甚至使用抽象类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何调用Java中存储在arraylist中的特定对象的方法? - How can I call a method of a specific object that is stored in an arraylist in Java? 我无法解释为什么对多态 object 的方法调用无法编译 - I can't explain why a method call on a polymorphic object will not compile 如何让JVM在多态方法调用中将scala.Array [T]识别为java数组T []? - How do make the JVM recognize a scala.Array[T] as a java array T[] in a polymorphic method call? 如何从 Java 反射性地调用 Scala object 上的方法? - How can I reflectively call a method on a Scala object from Java? 如何在数组上调用 get 方法 Object - Java - How to call get method on an Array Object - Java 如何安排Java抽象类的层次和多态方法调用和定义 - How to arrange Java abstract class hierachy and polymorphic method call and definition 如何检测 Java 中的方法调用? - How can I detect a method call in Java? 如何强制对超级方法进行多态调用? - How do I force a polymorphic call to the super method? 如何从Java调用MSSQL加密的存储过程? - How can I call MSSQL encrypted Stored Procedures from Java? 如何调用存储在字符串变量中的 Java 方法 - How to call Java method that stored in string variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM