从对象调用另一个方法-Java

Calling another Method from object-Java

我很难过。我在 (BedRoom) class 中创建了一个名为 "makeBed" 的方法,该方法调用了 (Bed) class 中另一个名为 "make" 的方法。但是当我尝试通过 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
}

卧室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();
}

}

床Class

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;
}
}

我想说的就是这样...您没有将代码包装到方法中,因此无法正确编译。

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
}
}

也许这会奏效。

这是假设这是你的 class 你想要从中初始化整个脚本,如果不改变 public static void main(String[] args){}public Main() {}