zoukankan      html  css  js  c++  java
  • java基础(八)之函数的复写/重写(override)

    复写的意思就是子类对父类的修改。

    复写的条件:

    1、在具有父子类关系的两个类当中;
    2、父类和子类各有一个函数,这两个函数的定义保持一致(返回值类型、函数名、参数列表)

    还是老样子,3个文件来说明。

     

    Person.java:

    class Person{
    	String name;
    	int age;
    	Person(){
    		
    	}
    	void introduce(){
    		System.out.println("My name is "+this.name +". My age is " +this.age);
    		
    	}
    }
    

      

    Student.java:

    class Student extends Person{
    	String address;
    	
    	void introduce(){
    		System.out.println("My name is "+super.name +". My age is " +super.age +". My home in " +this.address);
    	}
    }
    

      

    Test.java:

    public class Test{
    	public static void main(String[] args){
    		Student li = new Student();
    		li.name = "liming";
    		li.age = 18;
    		li.address = "china";
    		li.introduce();
    		
    		Person zhang = new Person();
    		zhang.name = "zhangsan";
    		zhang.age = 20;
    		zhang.introduce();
    	}
    }
    

      

    输出结果:

    PS C:UsersadminDesktopjava_code练习七> java Test
    My name is liming. My age is 18. My home in china
    My name is zhangsan. My age is 20
    PS C:UsersadminDesktopjava_code练习七>
    

      

     super调用父类函数

    修改Person.java:

    class Student extends Person{
    	String address;
    	
    	void introduce(){
    		super.introduce();
    		System.out.println("My name is "+super.name +". My age is " +super.age +". My home in " +this.address);
    	}
    }
    

      

    修改Test.java:

    public class Test{
    	public static void main(String[] args){
    		Student li = new Student();
    		li.name = "liming";
    		li.age = 18;
    		li.address = "china";
    		li.introduce();
    	}
    }
    

      

    输出结果:

    PS C:UsersadminDesktopjava_code练习七> java Test
    My name is liming. My age is 18
    My name is liming. My age is 18. My home in china
    

      

      

  • 相关阅读:
    AtCoder Beginner Contest 089 D
    AtCoder Beginner Contest 088 D Grid Repainting
    [odb-users] query results not being cached?
    cmake使用示例与整理总结
    CMake使用总结
    Create schema error (unknown database schema '')
    [odb-users] Create schema error (unknown database schema '')
    ODB(C++ ORM)用Mingw的完整编译过程
    odb_sqlite_demo
    ODB——基于c++的ORM映射框架尝试(使用)
  • 原文地址:https://www.cnblogs.com/endust/p/11814184.html
Copyright © 2011-2022 走看看