zoukankan      html  css  js  c++  java
  • java4android (继承中的子类实例化过程)

    生成子类的过程

    见代码:

    class Person {
        String name;
        int age;
        Person(){
            System.out.print("Person的无参数构造函数");
        }
        Person(String name,int age){
            this.name = name;
            this.age = age;
            System.out.print("Person的有2个参数的构造函数");
        }
        void eat(){
            System.out.print("吃饭");
        }
    }
    class Student extends Person{
        int grade;
        Student(){
            //在子类的构造函数当中,必须调用父类的构造函数
            //如果没有写父类的构造函数,那么编译器会自动加上 super();
            //super(根据参数调用父类中相应的构造函数);
            System.out.print("Student的无参数构造函数");
        }
        
        Student(String name,int age,int grade){
            //this.name = name;
            //this.age = age;
            super(name,age);//减少重复代码
            this.grade = grade;
        }
    }
    class Text{
        public static void main(String args[]){
            Student s = new Student("zhansan",18,90);
            System.out.print(s.name);
            System.out.print(s.age);
            System.out.print(s.grade);
        }
    }

    使用super调用父类构造函数的方法

    由于子类继承了父类的成员变量和成员函数,但无法继承父类的构造函数,所以在为成员变量赋值的时候会出现代码重复。为解决这个问题,用super调用父类的构造函数。。

    注意:super在构造函数中要在第一行。

  • 相关阅读:
    01点睛Spring MVC 4.1-搭建环境
    18点睛Spring4.1-Meta Annotation
    17点睛Spring4.1-@Conditional
    16点睛Spring4.1-TaskScheduler
    15点睛Spring4.1-TaskExecutor
    Zabbix4.0.3解决中文乱码
    A10映射方法
    源码安装zabbix_agent4.0.3
    单机部署redis5.0集群环境
    zabbix系列之九——添加钉钉告警
  • 原文地址:https://www.cnblogs.com/safiri/p/3735690.html
Copyright © 2011-2022 走看看