zoukankan      html  css  js  c++  java
  • Java构造函数 为什么子类有时需要在构造函数中调用super呢?

    Java在实例化一个对象的时候,如果没有显式使用super(),则会先调用父类的无参构造函数(不是和自己构造函数参数数量对应的那个),然后调用子类的构造函数,如果父类不是Object类,则一直向上追溯到Object类为止,super()只能在构造函数的第一行使用,在别的地方使用均为非法,一般情况下构造函数不用写super(),但是如果一个类有多个构造函数的时候,为了便于理解,往往要显式调用super()。

    下面示例代码的运行结果为:
    I am father
    I am son:baidu
    I am father
    I am son

    示例代码:
       1public class Test {  
       
    2.     public static void main(String[] args) {  
       
    3.         new Son("baidu");  
       
    4.         new Son();  
       
    5.     }  
       
    6. }  
       
    7.   
       
    8class Farther{  
       
    9.     public Farther(){  
      
    10.         System.out.println("I am father");  
      
    11.     }  
      
    12.   
      
    13.     public Farther(String name){  
      
    14.         System.out.println("I am father:"+name);  
      
    15.     }  
      
    16. }  
      
    17.   
      
    18class Son extends Farther{  
      
    19.     public Son(){  
      
    20.         System.out.println("I am son");  
      
    21.     }  
      
    22.     public Son(String name){  
      
    23.         //super("google");  
      24.         System.out.println("I am son:"+name);  
      
    25.     }  
      
    26. } 
  • 相关阅读:
    C#微信开发
    3-4:字符串方法
    2-4-1 元组
    2-3-3 列表方法
    2-2-3:序列(字符串)乘法(p32)
    3-3字符串格式化(p47)
    2-2:分片
    2-1:Print date(p28)
    old.2.三次登录机会
    old.2.sum(1-2+3-4+...+99)
  • 原文地址:https://www.cnblogs.com/super119/p/1924531.html
Copyright © 2011-2022 走看看