Home  >  Article  >  Java  >  How to override a method in java

How to override a method in java

王林
王林Original
2019-12-04 15:04:587315browse

How to override a method in java

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:

How to override a method in java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn