简体   繁体   English

如何从特定的 class 创建 object 并使用 java 中的方法更改其属性

[英]How do I create an object from a specific class and change its attributes by using methods in java

public class Forklift{
    double height;
    Forklift fl_1, fl_2;
    
    Forklift(){
        fl_1 = new Forklift();
        fl_2 = new Forklift();
    }

    void raise(){
        height += 10;
    }
    void lower(){
        height -= 10;
    }
}

I'm currently using BlueJ.我目前正在使用 BlueJ。 I want to create two objects with the attribute 'height' and I want to use the methods raise() and lower() to change the value of that attribute.我想创建两个具有属性“高度”的对象,并且我想使用方法 raise() 和 lower() 来更改该属性的值。 Can someone please help me?有人可以帮帮我吗? I don't know why it's not working我不知道为什么它不起作用

Are you trying to do something like this?你想做这样的事情吗?

public class Forklift{
    double height;
    
    Forklift(){
        height=0;
    }

    void raise(){
        height += 10;
    }
    void lower(){
        height -= 10;
    }
}

I dont understand why you are creating a forklift in the forklift constructor.我不明白你为什么要在叉车构造函数中创建叉车。 That just gives you an infinite loop.那只会给你一个无限循环。

Edit: If you want to create two instances of the class, just use:编辑:如果要创建 class 的两个实例,只需使用:

Forklift forklift1 = new Forklift();
Forklift forklift2 = new Forklift();

somewhere outside the class. Now you have two instances of the class. class 之外的某处。现在您有 class 的两个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建Java类对象并在PHP中运行其功能? - How do I create Java class object and run its functions in PHP? 如何在Java,C ++或任何面向对象语言中使用动态和变量属性时创建类? - How to create a Class when its attributes are dynamic & variable in Java, C++ or any Object-Oriented Language? Java:如何在静态方法中创建对象,还从另一个类调用方法? - Java: How do i create objects in a static method and also call for methods from another class? Java - 使用受保护的方法从不同的 class 更新 object 的属性 - Java - Update attributes of an object from a different class with protected methods 如何在 Java 中选择一个对象来更改其字段? - How do I choose an object in Java to change its fields? Java:如何使用类属性创建地图? - Java : How to create map using the class attributes? 如何使用在不同类中实例化的对象的方法? - How do I use methods from an object instantiated in a different class? 如何从FreeMarker模板调用对象上的java方法? - How do I call java methods on an object from a FreeMarker template? 如何从委托方法的类中创建对象? - How to create an object from a class that delegates methods? 我如何更改其他类中的变量,该变量将更改Java所有类中的值 - how do i change a variable in an others class that will change its value in all class in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM