zoukankan      html  css  js  c++  java
  • 5.4.1在构造函数中调用构造函数

    我们可以在自定义类中的构造函数中调用构造函数,但是有一定的规则。

    先看如下例子:

    public class Flower {
        int petalCount = 0;
        String s = "initial value.";
        
        Flower(int petals) {
            petalCount = petals;
            System.out.println("Constructor w/ int arg only, petalCount = " + petalCount);
        }
        
        Flower(String ss) {
            s = ss;
            System.out.println("Constructor w/ String arg only, s = " + s);
        }
        
        Flower(String ss, int petals) {
            this(ss);
            //s = ss;
            //this(petals);  Can't call two.
            petalCount = petals;
            System.out.println("String & int args");
            
        }
        
        Flower() {
            this("hi", 24);
            System.out.println("Default Constructor.");
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Flower f = new Flower();
            System.out.println(f.s);
            System.out.println(f.petalCount);
        }
    }

    output:

    Constructor w/ String arg only, s = hi
    String & int args
    Default Constructor.
    hi
    24

    还记得我之前写的,在C++语言中构造函数调用构造函数。在这一方面,C++和Java是截然不同的。以后利用的时候千万不要搅浑了。

    总结:

    1. 尽管可以用this()调用一个构造函数,但却不能调用两个。此外,必须将构造函数调用置于最起始处,否则编译会报错。

    2. 除了可以在构造函数中调用构造函数以外, 编译器禁止在其他方法中调用构造函数。

  • 相关阅读:
    从POJ1958引发对n盘m塔Hanoi问题的思考
    SPOJGSS3 Can you answer these queries III
    【模板】SPFA判负环(洛谷P3385)
    【模板】强联通缩点(洛谷P3387)
    Luogu P2186 小Z的栈函数
    Luogu P2129 小Z的情书
    LGBT学分块
    LGBT玩扫雷
    A 美丽的子树
    B(升降序列)
  • 原文地址:https://www.cnblogs.com/wiessharling/p/3334915.html
Copyright © 2011-2022 走看看