疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

java之方法的重写


 

   

  方法的重写:

  1、在子类中可以根据需要对从基类中继承来的方法进行重写。

  2、重写的方法和被重写的方法必须具有相同方法名称、参数列表和返回类型。

  3、重写方法不能使用比被重写的方法更严格的访问权限。

  程序code:

  class Person{

  private int age;

  private String name;

  public void setAge(int age){

  this.age = age;

  }

  public void setName(String name){

  this.name = name;

  }

  public int getAge(){

  return age;

  }

  public String getName(){

  return name;

  }

  public String getInfo(){

  return "Name is:"+name+",Age is "+age;

  }

  }

  class Student extends Person{

  private String school;

  public void setSchool(String school){

  this.school = school;

  }

  public String getSchool(){

  return school;

  }

  public String getInfo(){

  return "Name is:"+getName()+",Age is "+getAge()+",School is:"+school;

  }

  }

  public class TestOverRide{

  public static void main (String args[]){

  Student student = new Student();

  Person person = new Person();

  person.setAge(1000);

  person.setName("lili");

  student.setAge(23);

  student.setName("vic");

  student.setSchool("shnu");

  System.out.println(person.getInfo());

  System.out.println(student.getInfo());

  }

  }

  执行结果:

  Name is:lili,Age is1000

  Name is:vic,Age is23,School is:shnu