【发布时间】:2018-10-13 09:09:26
【问题描述】:
在子类和超类中创建子类的对象有什么区别?
我的超类是 -> LibraryItem.Java
我的子类是 -> Book.java
1和2有什么区别
1. LibraryItem book_01 = new Book() //In superclass
2. book_01 = new Book() //In subclass
注意:- 请注意我删除了一些 get、set 和一些抽象方法。这里只添加了重要的部分
public abstract class LibraryItem {
private boolean status;
private String borrowedDateTime;
private Reader reader;
private int isbn;
private String title;
private String publicationDate;
private String sector;
public abstract void getItemDetails();
public abstract void returnItem();
public abstract void readerDetails();
public abstract void borrowItem();
public static void main (String [] args){
}
}
public class Book extends LibraryItem {
public String author;
public String publisher;
public int no_Of_Pages;
private int readerID;
Book[] bookArray = new Book[100];
Book(int isbn, String title, String sector, String publicationDate,
boolean status, String borrowedDateTime, String author, String publisher, int no_Of_Pages, int readerId){
super();
this.setIsbn(isbn);
this.setTitle(title);
this.setSector(sector);
this.setPublicationDate(publicationDate);
this.setStatus(status);
this.setBorrowedDateTime(borrowedDateTime);
this.author = author;
this.publisher = publisher;
this.no_Of_Pages = no_Of_Pages;
this.setReaderID(readerId);
}
//Create 100 Books
public void createBooks(){
Book book_01;
book_01 = new Book(00001, "Harry Potter", "Adveture", "2012.12.12",
true, "asd","J.K Rowling", "Disney", 500, 0);
bookArray [0] = book_01;
}
}
【问题讨论】:
-
无论您在哪里创建类的实例,都应该没有区别。你到底想找到什么?
-
new Book();做同样的事情假设Book是同一个类。你有什么疑问? -
我在子类中有一个数组“ bookList [] ”,我想将对象添加到数组中。我想知道,根据真正的 OOP 规则,我应该在哪里创建对象。此外,该对象具有超类的属性,超类是抽象类和子类的属性。
-
您能否发布您的超类和子类的代码,并在您尝试在 bookList[] 数组中添加对象的位置显示您的代码?
-
如果您可以发布minimal reproducible example,它会更容易为您提供帮助。你在哪里做的详细信息可能很重要。