描述一个学生类 Student ,要求:
1)描述“学校”和“年龄”两个属性,其中,学校为全局共享属性,年龄为私有属性;2)为年龄属性创建两个方法,一个用于设置值,另一个用于获取值;
3)定义一个方法show0,用于输出某个学生“学校”和“年龄”的属性信息。
4)在测试类 Test 中创建一个对象 stu ,学校为“某某学校”,年龄为20。
运行结果:
代码:
Student.java
public class Student {
public static String school; //学校
private int age; //年龄
//获取年龄
public int getAge(){
return age;
}
//设置年龄
public void setAge(int a){
age = a;
}
//显示信息
public void show(){
System.out.println("school:"+school +",age:"+ age);
}
}
Test.java
ublic class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu = new Student();
Student.school = "北京外国语学校";
stu.setAge(20);
stu.show();
}
}
参考如下:
public class Student {
public static String school; // 学校
private int age; // 年龄
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void show0() {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("school=").append(school)
.append(",age=").append(age);
System.out.println(sBuilder.toString());
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student();
Student.school = "某某学校"; // 类共享,直接用Student引用
student.setAge(20); // 私有,需要实例调用
student.show0();
}
}
如有帮助,欢迎采纳哈!