首页 > 代码库 > 面向对象4
面向对象4
\\子类可以拥有父类的所有成员变量和方法,
\\子类可以对父类的方法进行重写
\\类的继承,方法的重写,
class Person {
private int id ;
private String name;
private int age;
public void setName (String name){
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setId (int id) {
this.id =id;
}
public int getId () {
return id;
}
public int getAge () {
return age;
}
public String getName () {
return name;
}
String getInfo () {
return "name : " + getName() +"\n" +"id :" + getId()+"\n"+"age :" +getAge();
}
}
\\继承
class Student extends Person {
private String school;
public void setSchool (String school){
this.school = school;
}
public String getSchool () {
return school;
}
\\重写
String getInfo () {
return "name :" + getName() +"\n" +"school : " + getSchool()+"\n"+"id : " + getId()+"\n"+"age : " +getAge();
}
}
public class TestOverWrite {
public static void main (String []args){
Student student = new Student();
Person person = new Person();
person.setName("Tom");
student.setName("Jarry");
person.setAge(80);
student.setAge(20);
person.setId(0);
student.setId(1);
student.setSchool("********");
System.out.println(person.getInfo());
System.out.println(student.getInfo());
}
}
面向对象4