简体   繁体   中英

How to call the variables (length,breadth,height) from another class constructor

How to call the variables (length,breadth,height) from another class constructor

trying to call the variables length,breadth,height from class A

unable to do so

   class A {
            int length;
            int breadth;
             int height;
        A(int length,int height,int breadth)
        {
            this.length=length;
            this.height=height;
            this.breadth=breadth;
        }   

    }

    class B extends A
    {      
            public void display()
        {
            System.out.println("Length of the rect is "+length);
            System.out.println("Height of the rect is "+height);
            System.out.println("Breadth of the rect is "+breadth);
        }

    }
    class Inheritence
    {
        public static void main(String [] args)
        {
            new A(5,6,7);
            new B().display();
        }
    }

I trying to call the variables length,breadth,height from class A

No you probably want to use variables from an A instance .

I think that what you need is a copy constructor defined in B that takes as parameter a A .

So define it in B such as

public B(A a){
   super(a.length, a.breadth, a.height);
}

And now you can do :

A a = new A(5,6,7);
new B(a).display();

A objA = new A(5,6,7) - makes an object called objA and sets properties length , breadth and height to 5,6,7 respectively.

B objB = new B() - makes an object called objB with new properties length , breadth and height and doesn't set them at all, so there is nothing to display.

If you want to set the values to properties of class B , make the constructor in class B and assign the values to fields length , breadth and height which are inherited from A .

There are 2 things you need to do:

  1. Change the access modifier to protected (read about it here )
  2. Create a constructor in B that sets the values for these parameters, eg

    public B(int length, int breadth, int height) { super(length, breadth, height); }

Once done, B will have access to these members and you will be able to print the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM