类如何使用Java中另一个类中定义的方法?

时间:2016-03-30 11:13:29

标签: java

如何使用getvolume()类中Box类定义的boxweight方法?我知道我必须实例化Box类才能使用它定义的方法,但是如何?

class Box {
    private int lenght;
    private int breadth;
    private int height;
    int price;

    Box(int l, int b, int h) {
        lenght= l;
        breadth= b;
        height= h;
    }

    public Box(int p) {
        price= p;
    }

    double getvolume() {
        return lenght*height*breadth;
    }

    void setsize(int $l, int $b, int $h  ) {
        lenght= $l;
        breadth= $b;
        height= $h;
    }
}

public class boxclassdemo {
    public static void main(String[] args) {
        Box mybox1=new Box(10,10,10);
        Box mybox2=new Box(5,5,5);
        Box mybox3=new Box(20);

        System.out.println(mybox1.getvolume());
        System.out.println(mybox2.getvolume());
        System.out.println(mybox3.price);
    }
}

拳击等级:

public class boxweight  {
    int weight;
    int length,breadth,height;  
    public static void main(String[] args) {
        boxweight myboxx =  new boxweight();
        myboxx.weight= 25;
        myboxx.length=10;
        myboxx.breadth=20;
        myboxx.height=30;
    }
}

3 个答案:

答案 0 :(得分:1)

您可以找到问题的答案,以及您在Oracle Java Tutorial on Object Creation

上无疑将会遇到的许多其他问题。
As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:

Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.

实际使用这些内容同样如此,the very next tutorial

Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:

objectReference.fieldName

我建议你要么开始阅读这些教程,要么给自己一本好的java书,那里有很多。

答案 1 :(得分:0)

(顺便说一句,班级名字的第一个字母通常是向上的 如果您使用Eclipse或其他IDE,它将帮助您在执行后续步骤时创建
Box box = new Box(25, 10, 20, 30);
然后,
System.out.println(box.getvolume());

答案 2 :(得分:0)

看起来好像要使用继承。如果您像这样定义BoxWeight,请注意类名后面的“extends Box”:

public class BoxWeight extends Box {
    int weight;

    BoxWeight(int l, int b, int h, int w) {
        super(l, b, h);
        weight = w;
    }
}

然后你可以将boxweight对象视为Box对象,这意味着你可以使用它的公共方法,如下所示:

public static void main(String[] args) {
    BoxWeight myboxx =  new BoxWeight(10, 20, 30, 25);
    double volume = myboxx.getvolume();
}