繁体   English   中英

如何从另一个类构造函数调用变量(长度,宽度,高度)

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

如何从另一个类构造函数调用变量(长度,宽度,高度)

试图从A类调用变量的长度,宽度,高度

无法这样做

   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();
        }
    }

我试图从A类中调用变量的长度,宽度,高度

不,您可能想使用A 实例中的变量。

我认为您需要的是在B中定义的复制构造函数,该复制构造函数将A作为参数。

因此在B定义它,例如

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

现在您可以:

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

A objA = new A(5,6,7) -使得称为对象objA和设置属性lengthbreadthheight ,以5,6,7分别。

B objB = new B() -使名为objB的对象具有新的lengthbreadthheight并且根本不设置它们,因此没有任何显示。

如果要将值设置为类B属性,请在类B构造该构造函数,并将这些值分配给从A继承的字段lengthbreadthheight

您需要做两件事:

  1. 将访问修饰符更改为保护(请在此处阅读)
  2. 在B中创建一个构造函数,为这些参数设置值,例如

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

完成后, B将有权访问这些成员,您将能够打印这些值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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