我刚刚了解了构造函数,并且必须在最近的程序中使用它们。我做对了,但我仍然不明白他们做了什么。如果有人可以使用这个程序给我一个详细的解释作为参考,这将是伟大的!
MAIN CLASS
public class Student
{
public static void main(String[]args)
{
String question, name, GPAStr, studentNumberStr;
int studentNumber;
double GPA;
question = JOptionPane.showInputDialog("Would you like to see if you Qualify for the Dean's List? (Y or N)");
while (question.equalsIgnoreCase("Y"))
{
name = JOptionPane.showInputDialog("Please enter your name.");
studentNumberStr = JOptionPane.showInputDialog("Please enter your student number.");
studentNumber = Integer.parseInt(studentNumberStr);
GPAStr = JOptionPane.showInputDialog("Please enter your GPA.");
GPA = Double.parseDouble(GPAStr);
StudentIO students = new StudentIO(name, GPA);
// ouput
JOptionPane.showMessageDialog(null, students.getDeansList());
question = JOptionPane.showInputDialog("Would you like to see if you Qualify for the Dean's List? (Y or N)");
if (question.equalsIgnoreCase("N"))
//display the content of players processed
{
JOptionPane.showMessageDialog(null,StudentIO.getCount());
}
}
}
}
第二类(其中包含建筑师的标签)
public class StudentIO
{
//instance fields
private String name;
private double GPA;
// static fields
private static final double GPAMIN=3.0;
private static int count = 0;
public StudentIO(String theName, double theGPA) // constructor
{
name = theName;
GPA= theGPA;
count = count +1;
}
public StudentIO() //no arg constructor
{
name = " ";
GPA = 0;
count = count +1;
}
public void setName(String theName)
{
name = theName;
}
public void setGPA(double theGPA)
{
GPA = theGPA;
}
public String getName()
{
return name;
}
public double getGPA()
{
return GPA;
}
public String getDeansList()
{
if(GPA >= GPAMIN)
return (name + ", has made the Dean's List!");
else
return(name + ", did not make the Dean's List!");
}
public static String getCount()
{
return ("You processed " + count + "students.");
}
}
答案 0 :(得分:1)
StudentIO students = new StudentIO(name, GPA);
将创建一个名为students的StudentIO对象,并影响使用第一个承包商创建的对象的名称和GPA参数:
public StudentIO(String theName, double theGPA) // constructor
{
name = theName;
GPA= theGPA;
count = count +1;
}
这相当于召唤:
StudentIO students = new StudentIO();
students.setName(name);
students.setGPA(GPA);
将使用seconde承包商:
public StudentIO() //no arg constructor
{
name = " ";
GPA = 0;
count = count +1;
}
使用两种方法
public void setName(String theName)
{
name = theName;
}
public void setGPA(double theGPA)
{
GPA = theGPA;
}
最后,这两种方法给你的结果相同,它的风格很重要,有时我们被迫在强耦合对象中使用秒数。
答案 1 :(得分:0)
count = count +1;
看来你在构造函数中指的是这一行。变量count
是StudentIO
类中的静态成员,用于跟踪使用参数化或默认构造函数创建的StudentIO对象的数量。
答案 2 :(得分:0)
StudentIO
类的构造实例。它们的目的是为StudentIO
的新实例设置初始状态。每个实例都有自己的状态。静态变量在实例之间共享,因此在每个构造中,您将向计数中添加一个。它会告诉你已经创建了多少个实例(我猜)。