Ok, so I'm in need of some basic help. Here's the tutorial I'm trying to learn from (http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html), but I'm confused as to how to actually pass data into it. The problem is I've got my Pascal brain on when trying to learn java...
Here's my code. What am I doing wrong?
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);
}
}
}
Thanks in advance for the help :)
解决方案
Constructor is not just a method: you need to give it the same name as the class, and call it with a new operator, like this:
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");