类和对象的案例讲解
类和对象的案例讲解
我们来写一个教室小测试:
1.我们先来创建一个学生类 ,有名字,年龄,性别,(构造函数,gat和set)
然后创建一个方法定义学生在上课。
在创建一个老师类 ,老师的姓名,性别,年龄 (构造函数,gat和set)
创建一个测试类进行运行。
1.创建学生类:
public class Student {
String name;
int age;
String sex;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
定义方法:
public void study(){
System.out.println("学生在上课");
}
创建老师类:
public class Teacher {
String name;
int age;
String sex;
public Teacher(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public Teacher() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
创建测试类调用方法:
public static void main(String[] args) {
Student student = new Student("小磊", 18, "男");
student.study();
Teacher teacher = new Teacher("小含", 20, "女");
System.out.println("老师姓名"+teacher.getName()+"年龄"+teacher.getAge()+"性别"+teacher.getSex());
System.out.println("姓名"+student.getName()+"年龄"+student.getAge()+"性别"+student.getSex());
}
首先在new对象,然后在穿参数,使用gai调用方法