我的程序常见错误(多态/覆盖/继承)

时间:2015-02-08 17:47:10

标签: java inheritance polymorphism abstraction

嗨,我知道你可以在这里轻松找到错误,我需要帮助解决这个问题 我很难找到我的代码有什么问题,我试图解决它但是当我试图改变某些东西时它会变得复杂

这是我目前的代码:

 package copro;

public class QuizInherit {
    public static void main(String[] args){

        students persons[] = new students[3];
        persons[0] = new students("Vincent","Dimalanta",90,85,80);
        persons[1] = new students("Daryl", "De Guzman", 95, 92, 91);
        persons[2] = new students("Jayson", "Elizaga", 88, 87, 86);

        for (students person : persons) {
            person.print();
        }
    }

    public class students extends Calculations {

        private String firstname;
        private String lastname;

        public students(String firstname, String lastname, int Grade1,
                int Grade2, int Grade3) {
            super(Grade1, Grade2, Grade3);
            this.firstname = firstname;
            this.lastname = lastname;
        }

        public void print() {
            System.out.println("FirstName: " + firstname);
            this.print();
            System.out.println("LastName: " + lastname);
            this.print();
            this.getAve();
        }
    }

    public class Calculations {

        private int Grade1;
        private int Grade2;
        private int Grade3;
        private double ave;

        public Calculations(int Grade1, int Grade2, int Grade3) {
            this.Grade1 = Grade1;
            this.Grade2 = Grade2;
            this.Grade3 = Grade3;
            this.ave = ave;
        }

        public void getAve() {
            ave = (Grade1 + Grade2 + Grade3) / 3;
        }

        public void print() {
            System.out.println("Student Details: ");
            this.print();
            System.out.println("Grade1: " + Grade1);
            System.out.println("Grade2: " + Grade2);
            System.out.println("Grade3: " + Grade3);
            System.out.println("The average is: " + ave);
        }

    }
}

错误在于:

persons[0] = new students("Vincent","Dimalanta",90,85,80);

我希望你会帮助我,我知道这是一个非常简单的问题,但对我来说很难,因为我现在是编程世界的初学者

谢谢

1 个答案:

答案 0 :(得分:0)

for (students person : persons) {
        person.print();
    }

上述代码调用,

`public void print() {
     System.out.println("FirstName: " + firstname);
     this.print();
     System.out.println("LastName: " + lastname);
     this.print();
     this.getAve();
 }`

通过print()递归调用this.print()。这可能会创建stackoverflow