学习在类里面创建对象和访问方法我怎么能...?

时间:2013-02-08 11:43:08

标签: java object constructor instance-variables

我的执行显示了这个错误:

  

java.lang.NoSuchMethodError:main

我需要将学生的详细信息作为输出。该程序应该访问所有上述方法。

 import java.io.*;
    import java.io.IOException;

    public class Student {
        String name;
        int age;
        String clas;
        int rank;
        int ID;

        public Student(String name){
        this.name = name;
        }

        public void studAge(int studAge)
        {
            age=studAge;
        }
        public void studClas(String studClas)
        {
            clas=studClas;
        }
        public void studRank(int studRank)
        {
            rank=studRank;
        }
        public void studID(int studID)
        {
            ID=studID;
        }
        public void displayStud()
        {
            System.out.println("Student Age is:"+age);
            System.out.println("Student Class is:"+clas);
            System.out.println("Student Rank is:"+rank);
            System.out.println("Student ID is:"+ID);
        }
    }
    class StudRecord{
       public static void main(String [] args)throws IOException
       {            
        Student studOne=new Student("Faraz");
        Student studTwo=new Student("Musheer");
        Student studThree=new Student("Imdad");
        Student studFour=new Student("Shahid");

        // Invoking methods for each object created         
        studOne.studAge(23);
        studOne.studClas("11th");
        studOne.studID(130018);
        studOne.studRank(16);

        studFour.studAge(21);
        studFour.studClas("11th");
        studFour.studID(130035);
        studFour.studRank(33);

        studTwo.studAge(26);
        studTwo.studClas("10th");
        studTwo.studID(130021);
        studTwo.studRank(2);

        studThree.studAge(24);
        studThree.studClas("11th");
        studThree.studID(130032);
        studThree.studRank(32);

        System.out.println();           
       }
   }

1 个答案:

答案 0 :(得分:0)

在Java中,文件中只有一个类可以标记为public。在这种情况下,类Student被标记为public,因此抛出NoSuchMethodException,因为main方法不在Student类上,而是在StudRecord类上。

因此,将StudRecord类更改为public,将Student类更改为默认访问(无访问修饰符)。