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
    

      

      

  • 相关阅读:
    solidworks 学习 (二)洗手液瓶
    solidworks 学习 (一)螺丝刀
    tensorflow 2.0 学习(三)MNIST训练
    tensorflow 2.0 学习(二)线性回归问题
    tensorflow 2.0 学习(一)准备
    sscanf linux-c从一个字符串中读进与指定格式相符的数据
    Linux-c glib库hash表GHashTable介绍
    Linux-c给线程取名字
    linux-c getopt()参数处理函数
    golang Linux下编译环境搭建
  • 原文地址:https://www.cnblogs.com/endust/p/11814184.html
Copyright © 2011-2022 走看看