首页 > 学院 > 开发设计 > 正文

java之方法的重写

2019-11-14 21:15:10
字体:
来源:转载
供稿:网友
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());    }}

执行结果:


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表