我在java的前几周,我理解这些概念之间的关系,但我试图在实例化过程中将值传递给子对象,而我却错过了关于这些部分如何组合在一起的东西。为什么我会收到错误?如何构造我的代码/我缺少哪种语法能够创建一个子实例然后打印该对象的值?
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);
}
你混淆了构造函数和main方法。
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);
}
}
此外,在调用函数时,请不要添加要传递的参数的类型。