Yahoo Answers is shutting down on 4 May 2021 (Eastern Time) and, as of 20 April 2021 (Eastern Time), the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Java coding problem?

class MultiLevelConstructors

{

    public static void main(String arg[])

    {

        X x = new X(10);

        Y y = new Y(11, 21);

        Z z = new Z(12, 22, 32);

    }

}

class X

{

    int i;

    X(int i)

    {

        this.i = i;

    }

}

// create a class ‘Y’ that extends from class ‘X’ and write a constructor that calls immediate parent constructor

// create a class ‘Z’ that exten ds from class ‘Y’ and write a constructor that calls immediate parent constructor

2 Answers

Relevance
  • 2 months ago

    You can call a constructor in a parent class using the "super" keyword.

    class Bird {

         Bird () { ... }

         Bird (int i) { ... }

    ...

     class Chicken extends Bird { 

          Chicken (int i) {  super (i); ... }

          Chicken (int i, int k) { super (i); /* code to handle k */ ... }

    ...    

    'super' can also be used to access other members of the parent class. For example, suppose the Bird class had a method fly (int). A method in Chicken could invoke Bird.fly (int): 

    super.fly (3); 

  • 2 months ago

    Here's the bare bones of a class YS that extends X to add a "name" string:

    class YS extends X

    {

        private String theName; // instance fields should almost always be private

        public YS(int i, String name) {

            super(i); // use base class constructor to fill in i field

            this.theName = name; // save value that's part of a Y object, but not in X

        }

        // public method to provide name of this instance:

        public string name() { return this.theName; }

    }

    Your version of Y needs an int instead of a String as the new value that's present in a Y object but not in a plain X object.  That's an easy change.

    Extending Y to make Z follows the same pattern, but the Z() constructor will take *three* arguments (i, j, k) and pass two of them (i, j) to super().  The Z class does not care that Y extends X.  All it knows is that it extends Y and the Y constructor wants values for i and j.  So Z won't mention X.  It will extend Y and have a super(i, j); call to start its constructor.

Still have questions? Get answers by asking now.