2017-01-23 39 views
-1

如果標題太模糊/不夠好,我會開始說我很抱歉,我很難用一行標題來表達我的問題。Java - 嘗試理解抽象類繼承和子類對象比較

我正在爲我的數據結構類進行項目工作,我一直在圍繞抽象類的繼承以及如何通過子類,對象比較,方法參數等操作它。我一整晚都在閱讀StackOverflow文章/ java教程(現在差不多4個小時),雖然我學了很多東西,但我還是不理解一些東西。我沒有在Java編碼在2年以上,並已使用大多數是C近來一直非常我感覺很生疏和不知所措:/

項目概況

我被要求建立各種各樣的數據庫代表我的大學學生和教授的數據。我有一個抽象超類,Person,它有兩個子類StudentInstructor。最後(我目前正在處理的課程)是一個名爲UniversityPeople的課程,其中引用了一組Student[]對象以及一組Instructor[]對象。 UniversityPeople類的方法有add(),delete(),search(),驗證數據等。爲2個對象數組。我知道這個實現看起來很奇怪,但不幸的是我必須按照說明操作。我試圖使這兩種方法無縫地工作,這部分是我感到困惑的地方。我會盡力組織我的問題盡我所能:

1.)這是一個普遍的問題,但我認爲對理解繼承很重要。我已經完成了大量的閱讀,但我仍然很困惑。如果我創建一個使用超類的類型但是子類對象的對象,如:Person newStudent = new Student(),該對象是否可以訪問它自己的類中的方法,還是僅限於超類方法?我的理解是,如果超類是abstract,孩子仍然以這種方式實例化時繼承他們的方法。

2.)我很難理解如何區分方法中的兩個對象數組。例如,我正在編寫一個clear()函數,該函數在調用時將指定的對象數組(Student[]Instructor[])設置爲null。我第一次嘗試使用instanceOf方法來測試數組是什麼類型,但編譯器警告我,我不能將類型學生投給Person或類似的東西。這裏是該類的構造函數以及我遇到的明確函數。我不知道如果我理解如何充分繼承在這裏工作,所以如果有更好的方法請賜教:

構造:

//Global declarations 
    //Declares arrays of student and instructor classes 
    private Student[] studentArray; 
    private Instructor[] instArray; 
    private int studentCount; 
    private int instCount; 

     /* 
     checks user input. If user enters 1, create student array. 
     if user enters 2, create Instructor array 
     */ 
     public UniversityPeople(int type, int size) 
     { 
      if (type == 1) 
      { 
       studentArray = new Student[size]; 
      } 
      else if (type == 2) 
      { 
       instArray = new Instructor[size]; 
      } 
     } 

單獨的插入方法,讓學生/教師,因爲我不能」牛逼想出一個辦法做到1, 如果它甚至有可能:

/* 
    checks if array is full or duplcate id exists. 
    If not, new Student object is created and 
    inserted into the student array 
    */ 
    public void insertStudent(String lastName, String firstName, int id, 
           int age, String yearStanding, double GPA) 
    { 
     boolean checkFull = isFull(); 
     boolean checkId = containsID(studentArray, id); 

     if (checkFull) 
     { 
      System.out.println("Array is full. Please delete a data member."); 
     } 
     else if (checkId) 
     { 
      System.out.println("Duplicate ID. Please check data and re-enter."); 
     } 
     if (!checkFull && !checkId) 
     { 
      Student newStudent = new Student(lastName, firstName, id, age, yearStanding, GPA); 
      newStudent = studentArray[studentCount]; 
      studentCount++; 
     } 
     else 
      System.err.println("There was an error while attempting to \n" + 
           "process your request. Please check your \n" + 
           "data entry and try again."); 

    }//end insertStudent 

    /* 
    checks if array is full or duplicate id exists. 
    If not, new Instructor object is created and 
    inserted into instructor array 
    */ 
    public void insertInstructor (String lastName, String firstName, int id, 
            int age, int officeNum, String subjectTaught) 
    { 
     boolean checkFull = isFull(); 
     boolean checkId = containsID(instArray, id); 

     if (checkFull) 
     { 
      System.out.println("Array is full. Please delete a data member."); 
     } 
     else if (checkId) 
     { 
      System.out.println("Duplicate ID. Please check data and re-enter."); 
     } 
     if (!checkFull && !checkId) 
     { 
      Instructor newInstructor = 
          new Instructor(lastName, firstName, id, age, officeNum, subjectTaught); 
      newInstructor = instArray[instCount]; 
      instCount++; 
     } 
     else 
      System.err.println("There was an error while attempting to \n" + 
           "process your request. Please check your \n" + 
           "data entry and try again."); 

    }//end insertInstructor 

最後,方法找人從他們的ID和清除指定任何陣列的方法在數組中。我已經在大多數這些方法中使用了參數類型Person[],我希望這些方法都可以接受。

public int findPerson(Person[] array, int id) 
    { 
     for (int i = 0; i < array.length; i++) 
     { 
      if (array[i].getId() == id) 
      { 
       return i; 
      } 
     } 

     return -1; 
    } 

    //Sets specified array to null. I need to reset the count of objects in 
    //the specified array to 0, but i'm really confused about how that works. Below is the best 
    //understanding I could come up with 
    public void clear(Person[] array) 
    { 
     for (int i = 0; i < array.length; i++) 
     { 
      array[i] = null; 
     } 

     if (array.getClass().equals(Student.class)) 
     { 
      studentCount = 0; 
     } 
     else if (array.getClass().equals(Instructor.class)) 
     { 
      instCount = 0; 
     } 
     else 
     { 
      System.out.println("There was an issue validating the object type."); 
     } 
    } 

我很感激任何意見和建議。我對clear()方法的實現特別困惑,因爲我以前從來不需要做這種類型的對象比較。我不確定爲什麼運算符比較會給我奇怪的結果。我真的很想理解這個東西,這真的很棒,看起來很有用。如果你想讓我發佈更多的代碼,我可以,但是我覺得這可能足以說明我的觀點。再次感謝:)

+1

1.你在說什麼叫**動態方法綁定**。假設你聲明一個像這樣的對象:'Person ob = new Student();'現在,如果你使用'ob'來訪問'Person'類的方法,那麼原始方法將被調用,如果它沒有在'學生「,否則,將調用重寫方法。 2.'instanceof'是** NOT **的一種方法,如果這就是你的想法。這是一個運營商。如果ob是一個Student對象,那麼'ob instanceof Student'將返回true。只要忽略編譯器警告。 – progyammer

+0

@progy_rock謝謝你澄清1.),因爲它讓我很困惑。如果我打電話給'instanceOf'的方法,我可能會有錯誤,我很抱歉。我知道這是一個返回布爾值的比較運算符,我只是不確定它是否實現,我的編譯器讓我進一步懷疑自己。這是比較我寫的那種比較的首選方式嗎? – FuegoJohnson

+0

我在之前的評論中展示的是比較對象的方式。在你的代碼中,你想比較(而不是檢查)數組的基類型。你在那裏犯了一個小錯誤,這個錯誤已經被@SME_Dev在他們的答案中很好地指出和糾正了。就編譯器警告而言,您可以簡單地禁止這些警告,這些警告不會影響您的程序。看看這個:[什麼是Java中的SuppressWarnings(「unchecked」)?](http://stackoverflow.com/questions/1129795/what-is-suppresswarnings-unchecked-in-java) – progyammer

回答

1

對於明確方法:

array = new Person[array.length] // re-init arrayt ot it's inital size. 
studentCount = studentArrayl.length; 
instCount = instArray.length; 

應該給定數組重新初始化到正確長度的新的空數組和reasigne正確數量studentCount和instCount。

問候。

復仇女神。

+0

非常感謝。這似乎更清晰,更易於理解。所以我認爲在那種情況下可以接受參數ar' Person []數組? – FuegoJohnson

+0

,因爲我看到它是;-)。 – Nemesis

2

該對象是否可以訪問它自己的類中的方法,或者是否僅限於超類方法的 ?我的理解是,如果 超類是抽象的,那麼當以這種方式實例化時,孩子們仍然繼承他們的方法 。

無關緊要,無論超類是否爲abstract。子類inherits父類的方法和屬性。這些是否可以通過兒童課程取決於visibility modifiers

我很難理解如何區分方法中的兩個對象數組,如 。例如,我正在寫一個clear()函數,它在調用時將指定的對象數組(Student []或Instructor [])設置爲null。

你可以重載clear()方法,如:

public void clear(Student[] array) {...} 
public void clear(Instructor[] array) {...} 

或者(如果我正確理解你的例子的目的)在類定義與數組引用比較輸入數組的參考:

public void clear(Person[] array) { 
    if(array == this.studentArray) { 
     // clear students 
    } else if(array == this.instArray) { 
     // clear instructors 
    } 
} 

但是,如果你想實際比較陣列的類型,你可以這樣做:

array.getClass().equals(Student[].class) 

array instanceof Student[] 
+0

非常感謝,你幾乎涵蓋了我所困惑的一切。有時它只是用一定的方式來解釋事物。我從來沒有想過超載清晰的方法,這是一個好主意。我的第一次嘗試使用了你的最後一個例子,'if(array instanceOf Student [])'但我的編譯器嚇跑了我。在你看來,什麼在這種情況下是最好的選擇? – FuegoJohnson

+0

@FuegoJohnson請添加一個代碼示例,您可以在其中獲得編譯器警告。 'if(array instanceOf Student [])'不會產生編譯器警告,如果你在該if的範圍內進行類型轉換('Student [] temp =(Student [])array'),那麼它就是安全。 –

1

#1,是的,newStudent將有機會獲得它自己的方法也很超除非它是@Overrideñ。

對於#2,你很難過,因爲你的UniversityPeople類正在做太多的事情。這將成爲維護問題並且是代碼味道。 UniversityPeople違反單一責任原則。你的班級只應做一件事。爲什麼不做UniversityInstructorUniveristyStudent?但是,由於您遵循了說明,因此以下是您的清晰功能的主意。在你的數組之前,你可以在數組中獲得一個內容。說Person person = array[0];,那麼你可以做一個if (person instanceof Student),然後if (person instanceof Instructor)。這樣你就可以知道你的數組的類型並相應地進行操作。

+0

我知道說明是非常愚蠢的國際海事組織。即使沒有在java中編寫一段時間,並且看到我明顯應該使用2個類而不是1個。我必須在一個類中處理這兩個數組的事實是令我困惑的。你的建議非常有創意,謝謝。看到不同的觀點很酷 – FuegoJohnson