定义一个学生类(Student),属性有private的名字(name),public的年龄(age),和封装name属性的方法:setName(),getName(),编写Application,创建一个学生对象,设置name和age属性值,然后调用一个方法(此方法将对象作为参数传递,在方法中打印出学生的名字name和年龄age)。
public class Student {
private String name;
public int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
public class Application {
public static void main(String[] args) {
Student s = new Student();
s.setName("John Doe");
s.age = 20;
printStudentInfo(s);
}
public static void printStudentInfo(Student student) {
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.age);
}
}