Java already has the .toString() method, but we need to override it so that it prints out the data inside (e.g instance variables) the object, and not the hex value
public class studentMain{
public static void main(String[]args){
Student s1 = new Student(); //instance of the class
Student s2 = new Student("Jessie"); //takes name as parameter
Student s3 = new Student("Addison", 16); //takes name and age as parameter
System.out.println(s1.toString()); //Prints out Name: "" Age: 0;
}
}
//new file (object)
public class Student{
//instance variables
private String name;
private int age;
public Student(){//constructor, initiates all the data values to a standard value
//used for s1
name = "";
age = 0;
}
public Student(String newName){ // overloaded constructor
//used for s2, sets name right away
name = newName;
age = 0;
}
public Student(String newName, int newAge){ //overloaded constructor
//used for s3, sets name and age right away
name = newName;
age = newAge;
}
public String toString(){ //helper method
String info = "Name: " + name + "\\nAge: " + age;
return info;
}
}