I'm in my first few weeks of java and I understand the relationships between these concepts, but I'm trying to pass values to a child object during instantiation and I'm missing something about how the pieces fit together. Why am I getting errors and how do I structure my code/what syntax am I missing to be able to create an instance of child and then print that object's values?
package child;
import static child.Gender.FEMALE;
import static child.Gender.MALE;
public class Child {
private String name;
private int age;
private Gender Gender;
public void eat(){}
public void sleep(){}
public void cry(){}
public Child main(String name, int age, Gender gender) {
this.name = name;
this.age = age;
this.Gender = Gender;
return null;
}
Child childOne = new Child(String "tom", int 3, Gender MALE);
System.out.println(childOne);
//Child childTwo = new Child();
//Child childThree = new Child("Tammy",1,FEMALE);
}
You are confusing a constructor and the main method.
public class Child {
private String name;
private int age;
private Gender gender;
public void eat(){}
public void sleep(){}
public void cry(){}
public Child (String name, int age, Gender gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public void main(String[] args) {
Child childOne = new Child("tom", 3, Gender.MALE);
System.out.println(childOne);
}
}
Also, when calling a function, don't add the type of the argument you are passing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.