是否可以创建其实例变量已经是现有对象的对象?

时间:2010-04-14 23:12:23

标签: java object

例如我可以

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

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

...

2 个答案:

答案 0 :(得分:3)

当然。

请注意,参数列表应以,代替;

分隔
 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

答案 1 :(得分:2)