Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将一个方法从一个类调用到另一个类?_Java - Fatal编程技术网

Java 如何将一个方法从一个类调用到另一个类?

Java 如何将一个方法从一个类调用到另一个类?,java,Java,我需要知道如何获得这两种方法: public void setSerial(int ser) { serialNumber = ser; } 及 这是一个单独的类,它位于哪里 public void displayBoxes(){ DecimalFormat df = new DecimalFormat("0.000"); System.out.println(toString()); System.out.println("The re

我需要知道如何获得这两种方法:

public void setSerial(int ser)
{
    serialNumber = ser;
}

这是一个单独的类,它位于哪里

public void displayBoxes(){
        DecimalFormat df = new DecimalFormat("0.000");
        System.out.println(toString());
        System.out.println("The rectangle with the serial number " + ??? + " has the largest area: " + ???);
对于一个output,它类似于:

The rectangle of serial number 3 has the largest area: 9088.611
the question marks are where the numbers come into the print line.

您需要为要调用这些方法的类指定一个具有这些方法的类的对象,然后创建该对象,将其分配给变量,并调用这些方法

e、 g

现在,如果希望ClassB在其构造函数中调用此方法:

public ClassB {
   private ClassA myA = new ClassA();

   public ClassB() {
      myA.foo();
   }
}

应该是这样的:

public class MyClass
{
    public void setSerial(int ser)
    {
        serialNumber = ser;
    }

    public double computeArea()
    {
        return width*length;
    }
}
但这是行不通的:

public void displayBoxes(){
    MyClass myClass = new MyClass();
    DecimalFormat df = new DecimalFormat("0.000");
    System.out.println(toString());
    System.out.println("The rectangle with the serial number " + myClass.setSerial(12345) + " has the largest area: " + myClass.ComputerArea());
因为: A.setSerial方法无效。不返回任何内容。 BComputerArea方法不接受任何参数,因此不知道ComputerArea方法中的宽度和长度……

阅读此内容。
public class MyClass
{
    public void setSerial(int ser)
    {
        serialNumber = ser;
    }

    public double computeArea()
    {
        return width*length;
    }
}
public void displayBoxes(){
    MyClass myClass = new MyClass();
    DecimalFormat df = new DecimalFormat("0.000");
    System.out.println(toString());
    System.out.println("The rectangle with the serial number " + myClass.setSerial(12345) + " has the largest area: " + myClass.ComputerArea());