定义一个构造函数,它接受名称并在实例化期间将值 Jack 传递给您的学生实例。
public class User {
public String name;
public String surname;
public int age;
public static String companyname;
//Let's pretend this is fine
User student = new User("Jack");
public User(String name){
this.name = name;
}
}
- 在实例块中包含您的语句。
public class User {
public String name;
public String surname;
public int age;
public static String companyname;
//Let's pretend this is fine
User student = new User();
{
student.name = "Jack";
}
}
- 在类构造函数中初始化您的学生字段。
public class User {
public String name;
public String surname;
public int age;
public static String companyname;
//Let's pretend this is fine
User student = new User();
public User(){
this.student.name = "Jack";
}
}
但是,所有这些选项都没有什么意义,它们都是为了让您了解可以编写语句的上下文。
我假设您只是想用它的实际字段(name、surname、age 和companyname)定义一个 User,然后在“测试”上下文中声明一个 Student,例如 main方法,来测试你的类。这很可能是您尝试执行的操作:
public class User {
public String name;
public String surname;
public int age;
public static String companyname;
public User(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
public static void main(String[] args) {
User student = new User("Jack", "Black", 15);
}
}
另外,您应该将类的属性(其字段)定义为private。 public 访问修饰符通常用于对象(其方法)提供的服务。这也称为 information hiding 或 encapsulation。基本上,您想隐藏类的内部实现并保护其状态(其字段)免受任何滥用,例如分配不一致的值。您的方法是调节对内部状态的访问的“外层”,它们包含防止误用和对对象状态进行不一致更改的逻辑。
无封装
public class User {
public String name;
public String surname;
public int age;
public User(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
public static void main(String[] args) {
User student = new User("Jack", "Black", 15);
//misuse of the object's attributes
student.age = -20;
}
}
封装
public class User {
private String name;
private String surname;
private int age;
public User(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
public void setAge(int age) {
if (age < 0 || age > 120) {
return;
}
this.age = age;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
User student = new User("Jack", "Black", 15);
student.age = -20; //gives you an error, you cannot access anymore this field directly
student.setAge(-20); //It won't update its age to -20
System.out.println(student.getAge()); //It still prints 15
student.setAge(25); //Regulates the update and allows the assignment
System.out.println(student.getAge()); //Prints 25
}
}
这篇文章很好地解释了封装的概念:
https://www.geeksforgeeks.org/encapsulation-in-java/