好的,所以我需要一些基本的帮助。这是我正在尝试学习的教程(http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html),但我对如何将数据实际传入其中感到困惑。问题是我在尝试学习java时已经掌握了Pascal的大脑......
这是我的代码。我做错了什么?
public class OrigClass{
public static void main(String[] args){
StudentData(17, "Jack"); //error here: the method StudentData(int, String) is undefined for the type OrigClass
}
public class Student{
public void StudentData(int age, String name){
int sAge = age;
String sName = name;
System.out.println("Student Name: " + sName + " | Student Age: " + sAge);
}
}
}
提前感谢您的帮助:)
答案 0 :(得分:5)
构造函数不仅仅是一个方法:您需要为它指定与该类相同的名称,并使用new
运算符调用它,如下所示:
public class Student{
// Declare the fields that you plan to assign in the constructor
private int sAge;
private String sName;
// No return type, same name as the class
public Student(int age, String name) {
// Assignments should not re-declare the fields
sAge = age;
sName = name;
System.out.println("Student Name: " + sName + " | Student Age: " + sAge);
}
}
// This goes in the main()
Student sd = new Student(17, "Jack");
答案 1 :(得分:2)
如果我假设您已正确编写Student
类而未考虑 Java命名约定且StudentData
是方法,那么调用方法StudentData
的方法是不正确的。首先创建Student
类的对象,然后调用方法
更新:考虑学生是内部班级
public static void main(String[] args){
new OrigClass().new Student().StudentData(17, "Jack");// Considering Student is inner class
}
答案 2 :(得分:2)
您的代码中存在多个问题。
首先,您已将StudentData的构造函数定义为普通方法 - 构造函数没有返回类型。
其次,您需要使用new
关键字在Java中创建非基本对象。
public class OrigClass{
public static void main(String[] args){
new Student(17, "Jack");
}
}
public class Student{
public Student(int age, String name){
int sAge = age;
String sName = name;
System.out.println("Student Name: " + sName + " | Student Age: " + sAge);
}
}
答案 3 :(得分:1)
public class OrigClass {
public static void main(String[] args) {
Student obj = new Student();
obj.studentData(17, "Jack");
}
}
public class Student {
public void studentData(int sName, String sAge) {
System.out.println("Student Name: " + sName + " | Student Age: " + sAge);
}
}
答案 4 :(得分:0)
因此,首先,您不能从静态方法( public static void main( StudentData(int age,String name))中访问非静态成员String [] args))。因此,如果要从静态main方法中访问该方法,则需要执行以下操作:
下面是完整的代码,显示了如何实现所需的输出:
public class OrigClass{
public static void main(String[] args){
OrigClass obj= new OrigClass();
obj.getStudentData();
}
public void getStudentData(){
Student std = new Student();
std.StudentData(17, "Jack");
}
public class Student{
public void StudentData(int age, String name){
int sAge = age;
String sName = name;
System.out.println("Student Name: " + sName + " | Student Age: " + sAge);
}
}
}