Home > Enterprise >  How to change parts of an object
How to change parts of an object

Time:05-09

I have a java program that has a custom class, this is an example class to represent it

String material;
int inches;
String colour;
Boolean destroyed;

...

public void Box(String bmaterial, int binches, String bcolour, Boolean bdestroyed) {
        material =  bmaterial;
        inches =  binches;
        colour = bcolour;
        destroyed = bdestroyed;
Box delta = new Box("cardboard", "32", "brown", false)
    }

if I run System.out.println(delta.material); the output would be cardboard. How could I change the value of delta.material after declaring the delta variable.

CodePudding user response:

You have 2 options:

Using public fields

You can set your fields public, e.g.

public String material;

Then you can set it with

delta.material = "paper";

Using Setter and Getter (highly recommended)

Normally, the fields are set as private fields in a Java class. To access them, you have to use setter and getter:

public class Box {
   private String material;
   //other attributes

   //constructor
   
   public void setMaterial(String material) {
       this.material = material;
   }

   public String getMaterial() {
       return this.material;
   }

Now you can set it with

delta.setMaterial("paper");

And if you want to read the material:

delta.getMaterial();

CodePudding user response:

Here is an example I wrote to show what calling and editing a Method looks like. I was going to use your code but there was a lot of errors I didn't feel like messing with.

public class Main {
    static void test1() {
        System.out.println("This test message is shown when 'test1()' is called");
    }

    public void editedTest(String c) {
        System.out.println("This method has been edited using a parameter "   c);
    }


    public static void main(String[] args) {
        Main mine = new Main();

        test1();
        mine.editedTest("EDITED");
    }
}

Output: This test message is shown when 'test1()' is called

This method has been edited using a parameter EDITED

Process finished with exit code 0

here I made a new method called "test1' and "editedTest", test1 is called and return just as is and edited has more added later. I hope this helped.

  •  Tags:  
  • java
  • Related