您的位置 首页 技术

java中如何重写一个方法

方法的重写: 1、在子类中可以根据需要对从基类中继承来的方法进行重写。 2、重写的方法和被重写的方法必须具有相同方法名称、参数列表和返回类型。 3、重写方法不能使用比被重写的方法更…

方法的重写:

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

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

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

在线视频教程分享:java在线视频

示例如下:

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());    }}

执行结果:

2ee30ee53af9343ceccd1b81b8610a5.png

相关文章教程推荐:java语言入门

以上就是java中如何重写一个方法的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/9190.html

为您推荐

返回顶部