2016-03-30 4 views
-1

Я пытаюсь создать программу, которая подготавливает список заслуг студентов по их общим отметкам. Если общие оценки двух учеников одинаковы, то проверяются индивидуальные оценки разных предметов.Как вызвать метод подкласса из метода суперкласса?

on line 40 Я пытаюсь вызвать метод подкласса из определения метода суперкласса, но я получаю сообщение об ошибке.

import java.util.*; 


class Student{ 
int[] ph, ch, ma; 
int[] total; 
int[] total_sort; 

Student(){} 

// length of array and marks are received via constructor. 
Student(int x, int[] p, int[] c, int[] m){ 

    // an array of p,c,m along with 2 arrays of total marks is made. 
    total = new int[x]; 
    total_sort = new int[x]; 
    ph = new int[x]; 
    ch = new int[x]; 
    ma = new int[x]; 
    for(int i = 0; i < x; i++){ 
     ph[i] = p[i]; 
     ch[i] = c[i]; 
     ma[i] = m[i]; 
     total[i] = (p[i] + c[i] + m[i]); 
     total_sort[i] = total[i]; 
    } 

} 

// sorts the array accoring to the total marks 
void Sort(){ 

    for(int f = 0; f < total.length; f++){ 

     if(total[f] > total[f+1]) 
      total_sort[f] = total[f]; 

     // checks for higher maths marks. 
     else if(total[f] == total[f+1]){ 
      int m = Stud_new.mSort(f); 
      total_sort[f] = total[m]; 
     } 

    } 
} 

/* returns the index from original total array so as to identify the   students' name. 
* marks from sorted array are compared with original array to find the index of marks in originial array . 
* this index is used to find the students' name. 
*/ 
int GetList(int a){ 


     for(int j = 0; j < total.length; j++){ 

      if(total[j] == a) 
       return j; 
     } 


    return -1 ; 

} 

}

class Stud_new extends Student{ 

int cSort(int ci){ 
    if(ch[ci] > ch[ci + 1]) 
     return ci; 

    else if(ch[ci] < ch[ci + 1]) 
     return (ci + 1); 

    //else if(ph[pi] == ph[pi + 1]) 
     //csort(pi); 
} 

int pSort(int pi){ 

    if(ph[pi] > ph[pi + 1]) 
     return pi; 

    else if(ph[pi] < ph[pi + 1]) 
     return (pi + 1); 

    else if(ph[pi] == ph[pi + 1]) 
     return(cSort(pi)); 
} 

int mSort(int mi){ 

    if(ma[mi] > ma[mi + 1]) 
     return mi; 

    else if(ma[mi] < ma[mi + 1]) 
     return (mi + 1); 

    // checks higher phy marks 
    else if(ma[mi] == ma[mi + 1]) 
     return(pSort(mi)); 
} 

}

class Mlist{ 

public static void main(String args[]){ 

    // initializes the names and marks. 
    String[] name = {"foo", "bar", "baz"}; 
    int[] phy = {80,112,100}; 
    int[] chem = {100,120,88}; 
    int[] maths = {40, 68,60}; 

    Student stud = new Student(name.length, phy, chem, maths); 

    System.out.println("Name\tPhysics\tChemistry\tMaths\tName"); 

    // prints the merit list 
    for(int i = 0; i < name.length; i++){ 

     // index of name is received by a function call 

     /* STUD.TOTAL_SORT[i] IS STUDENTS' MARKS IN SORTED MANNER. 
     * THIS IS PASSED AS AN ARGUMENT TO GETLIST METHOD WHICH USES LINEAR SEARCH 
     * TO FIND THE INDEX IN THE ARRAY OF NAMES FOR THE STUDENT WHOSE MARKS IS PASSES 
     * THE FUNCTION RETURNS INT WHICH IS THE INDEX FOR NAME[] ARRAY. and others all well. 
     * HERE STUD.TOTAL_SORT[I] IS AN ARGUMENT TO THE FUNCTION STUD.GETLIST() WHICH RETURNS AN INT    
     */ 
      System.out.println(name[stud.GetList(stud.total_sort[i])]+"\t"+phy[stud.GetList(stud.total_sort[i])]+"\t"+chem[stud.GetList(stud.total_sort[i])]+"\t"+maths[stud.GetList(stud.total_sort[i])]+"\t"+stud.total_sort[i]); 
    } 


} 

}

+0

40-я строка '// set nu' – Kent

+0

[ссылка] (http://pastebin.com/VAeCRX4X) @Kent – shiwchiz

+0

Я считаю, что ваша проблема находится в' Stud_new.mSort (f) '. Вы пытаетесь сделать статический вызов нестационарного метода. – dambros

ответ

0

Вы, вероятно, ищете способ фабричной модели-эск решения. Пожалуйста, зайдите в Google для получения более подробной информации, но просто введите, вы хотите, чтобы класс Student был абстрактным и добавлял абстрактный метод mSort, а затем реализовал метод в классе Stud_new. Затем вам необходимо создать экземпляр объекта Stud_new.

Подсказка: вы можете сделать что-то вроде этого:

Student stud = new Stud_new(name.length, phy, chem, maths); 

Это далеко от идеального решения, но это решение позволяет вызвать метод из подкласса в суперкласс, который является именно то, что вы просили.

+0

хорошо, я думаю, я получил то, что вы пытаетесь сказать! – shiwchiz

0

Вызов метода подкласса из метода суперкласса невозможен, и это неправильно.

Это противоречит правилам наследования.

Суперкласс представляет собой обычное поведение, в то время как подкласс имеет специфическое поведение, которое не видно их суперклассу.

Смежные вопросы