The examples in this article describe java method rewriting and are shared with everyone for your reference. The specific analysis is as follows:
1. Overview of method rewriting:
1. In subclasses, methods inherited from the base class can be rewritten as needed.
2. The overridden method and the overridden method must have the same method name, parameter list, and return type.
3. Overriding methods cannot use more restrictive access permissions than the overridden method.
2. The program code is as follows:
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()); }}
The execution result is shown in the figure below:
I hope this article will be helpful to everyone’s Java programming.