从object-Java调用另一个方法

时间:2016-04-16 02:26:47

标签: java composition

我很难过。我在(BedRoom)类中创建了一个名为“makeBed”的方法,该方法调用名为“make”的(Bed)类中的另一个方法。但是当我尝试通过bedroom.makeBed()调用该方法时;这是行不通的。我把//放在我试图开始工作的部分。

主要

public class Main {
Wall wall1 = new Wall("West");
Wall wall2 = new Wall("East");
Wall wall3 = new Wall("South");
Wall wall4 = new Wall("North");

Ceiling ceiling = new Ceiling(12, 55);

Bed bed = new Bed("Modern", 4, 3, 2, 1);

Lamp lamp = new Lamp("classic", false, 75);

BedRoom bedroom = new BedRoom("test",wall1,wall2,wall3,wall4,ceiling,bed,lamp);

bedroom.makeBed(); //bedroom.makeBed(); does not work 
//It does not show the public method "makeBed" in the BedRoom class
}

BedRoom Class

public class BedRoom {
private String name;
private Wall wall1;
private Wall wall2;
private Wall wall3;
private Wall wall4;
private Ceiling ceiling;
private Bed bed;
private Lamp lamp;

public BedRoom(String name, Wall wall1, Wall wall2, Wall wall3, Wall wall4, Ceiling ceiling, Bed bed, Lamp lamp) {
   this.name = name;
    this.wall1 = wall1;
    this.wall2 = wall2;
    this.wall3 = wall3;
    this.wall4 = wall4;
    this.ceiling = ceiling;
    this.bed = bed;
    this.lamp = lamp;
}

public Lamp getLamp(){
    return this.lamp;
}

public void makeBed(){              //This is the method I'm trying to access
    System.out.println("Bedroom -> Making bed");
    bed.make();
}

}

床类

public class Bed {
private String style;
private int pillows;
private int height;
private int sheets;
private int quilt;

public Bed(String style, int pillows, int height, int sheets, int quilt) {
    this.style = style;
    this.pillows = pillows;
    this.height = height;
    this.sheets = sheets;
    this.quilt = quilt;
}

public void make(){ 
    System.out.println("Bed -< Making"); //Method I'm trying to call
}

public String getStyle() {
    return style;
}

public int getPillows() {
    return pillows;
}

public int getHeight() {
    return height;
}

public int getSheets() {
    return sheets;
}

public int getQuilt() {
    return quilt;
}
}

1 个答案:

答案 0 :(得分:2)

我想说这就是它...你没有将你的代码包装到一个方法中,所以它没有正确编译。

public class Main {
public static void main(String[] args) {
Wall wall1 = new Wall("West");
Wall wall2 = new Wall("East");
Wall wall3 = new Wall("South");
Wall wall4 = new Wall("North");

Ceiling ceiling = new Ceiling(12, 55);

Bed bed = new Bed("Modern", 4, 3, 2, 1);

Lamp lamp = new Lamp("classic", false, 75);

BedRoom bedroom = new BedRoom("test",wall1,wall2,wall3,wall4,ceiling,bed,lamp);

bedroom.makeBed(); //bedroom.makeBed(); does not work 
//It does not show the public method "makeBed" in the BedRoom class
}
}

也许这会奏效。

这是基于这样的假设,即如果不将public static void main(String[] args){}更改为public Main() {}

,则您希望将整个脚本初始化为您的班级