如何从另一个类构造函数调用变量(长度,宽度,高度)
试图从A类调用变量length,breadth,height
无法这样做
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();
}
}
答案 0 :(得分:2)
我试图从A类调用变量length,breadth,height
否,您可能不想使用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();
答案 1 :(得分:0)
A objA = new A(5,6,7)
-制作一个名为objA
的对象,并将属性length
,breadth
和height
分别设置为5,6,7
。
B objB = new B()
-使用新属性objB
,length
和breadth
制作一个名为height
的对象,并且根本不设置它们,因此存在什么也没显示。
如果要将值设置为类B
的属性,请在类B
中创建构造函数,并将值分配给字段length
,breadth
和{{ 1}}继承自height
。
答案 2 :(得分:0)
您需要做两件事:
在B中创建一个构造函数,以设置这些参数的值,例如
Assert
完成后,[Test]
[TestCase(12)]
[TestCase(50)]
[TestCase(100)]
[TestCase(300)]
public void Should_ReturnValueDescription_When_ValueBiggerThan10(int? value, bool isNullResult)
{
var mockTest = new Test(value);
Assert.IsNotNull(mockTest.ValueDescription);
}
[Test]
[TestCase(9)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
public void Should_ReturnValueDescription_When_ValueLowerOrEqualThan10(int? value, bool isNullResult)
{
var mockTest = new Test(value);
Assert.IsNull(mockTest.ValueDescription);
}
将有权访问这些成员,并且您将能够打印这些值。