[英]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
和设置属性length
, breadth
和height
,以5,6,7
分别。
B objB = new B()
-使名为objB
的对象具有新的length
, breadth
和height
并且根本不设置它们,因此没有任何显示。
如果要将值设置为类B
属性,请在类B
构造该构造函数,并将这些值分配给从A
继承的字段length
, breadth
和height
。
您需要做两件事:
在B中创建一个构造函数,为这些参数设置值,例如
public B(int length, int breadth, int height) { super(length, breadth, height); }
完成后, B
将有权访问这些成员,您将能够打印这些值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.