简体   繁体   English

从超类的arraylist访问子类方法

[英]Accessing subclass method from arraylist of superclass

For an assignment, I have an ArrayList of type "Reference". 对于赋值,我有一个类型为“Reference”的ArrayList。 Reference is a parent class to the "Book" class and "Journal" class. Reference是“Book”类和“Journal”类的父类。 If I am allowed to add objects of type "Book" and "Journal" to the Arraylist, why would I be getting an error if I want to access methods of Book and Journal via the following code? 如果允许我向Arraylist添加“Book”和“Journal”类型的对象,如果我想通过以下代码访问Book和Journal的方法,为什么会出现错误?

          ArrayList.get([someindex]).someBookorJournalMethod()

The arraylist itself is of the parent class, and the methods I want to access are only defined for either book or either journal. arraylist本身属于父类,我想要访问的方法仅针对书籍或任一期刊定义。

EDIT: Here is some code 编辑:这是一些代码

  public class Books extends Reference{

   private String Authors;
   private String Publishers;


      public Books(String CallNum, String Author, String Title, String Publisher, int year,String type)
      {

          super(CallNum,Title,year,type);

          Authors= Author;
          Publishers=Publisher;
      }

public String getAuthor()
{
    return Authors;
}



 public class LibrarySearch {


      private ArrayList<Reference> Library;


      public LibrarySearch()
      {
          Library = new ArrayList<Reference>(100);
      }


      public outputLibrary(){

      for (int i = 0 ; i < Library.size(); i+++)
      {
        if (Library.get(i).getType().equals("Book"))
        {
            System.out.println("Type:book\n" + "Call Number:" +  Library.get(i).getCallNumber() +"\n" + "Authors:" + Library.get(i).getAuthors();)
        }
    }

}

IntelliJ is having issues with the line Library.get(i).getAuthors() because it is a method specific to Books. IntelliJ遇到了Library.get(i).getAuthors()行的问题,因为它是一个特定于Books的方法。 How would I resolve this? 我该如何解决这个问题?

Because when you specify the type of a variable, you can only invoke methods that are defined for this type. 因为在指定变量的类型时,只能调用为此类型定义的方法。 For example, if you have 例如,如果你有

public class A {
  public void methodA() {
    System.out.println("A");
  }
}

public class B extends A {
  public void methodB() {
    System.out.println("B");
  }
}

public class Main {
  public static void main(String[] args) {
    A ab = new B();
    ab.methodB();
  }
}

This will not compile, since the type defined for the variable ab is A and the only visible methods are those that are defined in A . 这将无法编译,因为为变量ab定义的类型是A ,唯一可见的方法是在A中定义的方法。

In your case you can simply add a blank method in Reference (if you don't want to make the class abstract): 在您的情况下,您只需在Reference添加一个空白方法(如果您不想使该类抽象):

public void someBookorJournalMethod() {}

Or you can explicitly cast the object you're trying to invoke the method for. 或者您可以显式转换您尝试调用方法的对象。

However, it is important to note that both approaches are usually bad practices and should be avoided. 但是,重要的是要注意这两种方法通常都是不良做法,应该避免。 If it does not make sense to instantiate Reference objects, than make the class abstract and define someBookorJournalMethod as an abstract method. 如果实例化Reference对象没有意义,那么使类abstract并将someBookorJournalMethod定义为抽象方法。 In your code you're most probably using inheritance in a wrong way. 在您的代码中,您最有可能以错误的方式使用继承。

You can't access the method of a subclass from the superclass. 您无法从超类访问子类的方法。 So you'll need to cast to a Book or a Journal. 因此,您需要投射到书籍或期刊。

Reference r =ArrayList.get([someindex]);
if (r instanceof Book) {
    ((Book) r).someBookMethod();
} else if (r instanceof Journal) {
     ((Journal) r).someJournalMethod();
} 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM