gpt4 book ai didi

java - 是否可以创建实例变量已经存在的对象?

转载 作者:行者123 更新时间:2023-11-29 08:18:13 25 4
gpt4 key购买 nike

例如我可以拥有

class Dog
{
int legs;
Bone chewy;
Bone squeeky;

public Dog (Bone chewyO, Bone squeekyO)
{
this.legs = 4;
chewy = chewyO;
squeeky = squeekyO;
}

...

最佳答案

当然。

请记住,参数列表应由 , 分隔,而不是 ;

 public Dog (Bone chewy, Bone squeekyO) 

试试这个:

// Dog.java
class Bone {
private String name;
Bone( String name ){
this.name = name;
}
public String toString() {
return this.name;
}
}
class Dog {
int legs;
Bone chewy;
Bone squeeky;

public Dog (Bone chewyO, Bone squeekyO) {
this.legs = 4;
this.chewy = chewyO;
this.squeeky = squeekyO;
}
public String toString() {
return String.format("This dogs has: %d legs, and two bones: %s, %s", legs, chewy, squeeky );
}
public static void main( String [] args ) {
Bone a = new Bone("chewy");
Bone b = new Bone("squeeky");
Dog dog = new Dog( a, b );
System.out.println( dog );
}
}
$javac Dog.java
$java Dog
This dogs has: 4 legs, and two bones: chewy, squeeky

关于java - 是否可以创建实例变量已经存在的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2641685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com