1,继承(extends)
- public class OverWrite{
- public static void main(String[] args){
- Person person = new Person();
- Student student = new Student();
- person.setName("none");
- person.setAge(100);
- student.setName("Jobs");
- student.setAge(24);
- student.setSchool("XXU");
- System.out.println(person.getInfo());
- System.out.println(student.getInfo());
- }
- }
- class Person{
- private String name;
- private int age;
- public void setName(String name){this.name = name;}
- public void setAge(int age){this.age = age;}
- public String getName(){return name;}
- public int getAge(){return age;}
- public String getInfo(){
- return "name: "+name+"\n"+"age: "+age;
- }
- }
- class Student extends Person{
- private String school;
- public String getSchool(){return school;}
- public void setSchool(String school){this.school = school;}
- //重写父类的getInfo()方法,添加了学校显示
- public String getInfo(){
- return "Name: "+getName()+"\nage: "+getAge()+"\nschool: "+school;
- }
- }
- class Father{
- public int value; //若把public 改为private,则Child类将无法访问到
- public void printValue(){
- value = 100;
- System.out.println("Father's Value: "+value);
- }
- }
- class Child extends Father{
- private int value;
- //重写父类的printValue()方法,并调用父类的该方法
- public void printValue(){
- super.printValue(); //调用父类方法:super.方法名()
- value = 101;
- System.out.println("Child's Value: "+value);
- System.out.println(value);
- System.out.println(super.value); //调用父类变量:super.变量名
- }
- }
- public class SuperTest{
- public static void main(String[] args){
- Child c = new Child();
- c.printValue();
- }
- }