需求:使用java类描述一个学生,学生有 name 、age两个属性, 还具备一个功能就是比较年龄。
要求:
1. 一旦创建了学生对象,学生就有了对应的属性值。 (构造函数、this)
//学生类
class Student{
String name;
int age;
//构造方法
public Student(String name,int age){
this.name = name;
this.age = age;
//System.out.println("");
}
//公共行为-比较年龄
public void compareAge(Student s2){
if(this.age>s2.age){
System.out.println(this.name+"大");
}
else if(this.age<s2.age){
System.out.println(s2.name+"大");
}
else{
System.out.println("同龄");
}
}
}
class Demo6
{
public static void main(String[] args)
{
Student s1 = new Student("小王",59);
Student s2 = new Student("小李",19);
s1.compareAge(s2);
//System.out.println("Hello World!");
}
}