[英]A method that could return a Child Object from a Parent Array?
我正在尋找一種可以從父數組返回子對象的方法 - 這意味着如何使方法返回子對象?
問題是我有這個方法可以從數組中返回一個父對象,但是在程序中我需要一個具有自己屬性的子對象,並且該數組有 3 種不同類型的子對象
這是我到目前為止:
class Store {
private BookParents store[];
private int ind, max;
public Store() {
ind=0; //Begin 0 and change with the method AddBooks;
max=100;
store = new BookParents[100];
}
public String AddBooks(BooksChild1 a){
if(ind<max){
store[ind++]=a;
return "TheBooksChild added correctly";
}
return "Full store";
}
public String AddBooks(BooksChild2 b){
if(ind<max){
store[ind++]=b;
return "TheBooksChild added correctly";
}
return "Full store";
}
public String AddBooks(BooksChild3 c){
if(ind<max){
store[ind++]=c;
return "TheBooksChild added correctly";
}
return "Full store";
}
public BooksParents SearchBook(String c) {
AnyBookChild null1 = new Book1("Unknown", 0,"Unknown","Unknown","Unknown","Unknown","Unknown");
if(ind!=0){
for(int i=0 ;i<ind;i++){
if(c.compareTo(store[i].getName(store[i]) )==0)
System.out.println(store[i].PrintlnBook());
return store[i];
}
System.out.println("Book didn't find, try another name.");
return null;
} else {
System.out.println("There is not books in the store");
return null;
}
}
}
由於您有多個 BooksChild 類,因此您將需要 BooksChild 類擴展的 BookParents 類。 您仍然可以使用 BookParents 數組:
store = new BookParents[100];
在每個 BooksChild 中,您將使用一個如下所示的構造函數:
public class BooksChild1 extends BookParents{
String myISBN, myTitle, myAuthor;
public BooksChild1(String isbn, String title, String author){
super(1, isbn, title, author); //1 denotes the class type
}
}
在 BookParents 類中,您將擁有另一個構造函數:
public class BookParents{
int myType;
String myISBN, myTitle, myAuthor;
public BookParents(int type, String isbn, String title, String author){
//when a new BooksChild1 is created, it will set the myType equal to 1
myType = type;
myISBN = isbn;
myTitle = title;
myAuthor = author;
}
//this accessor will allow you to find the type of BooksChild
public int getMyType(){
return myType;
}
}
`
現在對於商店部分,將 BooksChild 添加到 BooksParent 數組:
public class Store{
//these declarations must be public if you want to use them in a public methods
public BookParents store[];
public int ind, max;
public Store() {
ind=0; //Begin 0 and change with the method AddBooks;
max=100;
store = new BookParents[100];
}
public String addBook(BookParnets bp){
/*must be max-1 or otherwise it will try
to push a final ind of 100 which is out of bounds*/
if(ind<max-1){
store[ind++]=bp;
return "TheBooksChild added correctly";
}
return "Full store";
}
}
當您聲明 BooksChild 類型對象以將 BooksChild1 插入您的商店時,最后一部分將存在於您的驅動程序類中,BooksChild1 的聲明語句如下:
BookParents b = new BooksChild1("isbn", "title", "author");
如果您需要在您的商店數組中查找 BooksChild 的類型,您可以使用以下命令返回類型(讓 store[0] 包含一個未知類型的 BooksChild):
store[0].getMyType();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.