Rewriting of methods:
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. The overridden method cannot use more restrictive access permissions than the overridden method.
Online video tutorial sharing: java online video
The example 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()); } }
Execution result:
Recommended related articles and tutorials: Getting started with java language
The above is the detailed content of How to override a method in java. For more information, please follow other related articles on the PHP Chinese website!