Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom class object's value with '=' operator in Java

I have a custom object that has a single value of type int that I wanting to do processing on to keep this value in a set range. My question is this: Given the following class, can I set it's value with myObject = 0;

public class foo{
    private int bar;
    public foo(){
    }
}

Instead of creating a method public void setBar()

like image 730
Xandor Avatar asked Aug 22 '13 17:08

Xandor


People also ask

How do you assign a value to a class object in Java?

First, define a class with any name 'SampleClass' and define a constructor method. The constructor will always have the same name as the class name and it does not have a return type. Constructors are used to instantiating variables of the class. Now, using the constructors we can assign values.

How do you assign an object to an object in Java?

If we use the assignment operator to assign an object reference to another reference variable then it will point to the same address location of the old object and no new copy of the object will be created. Due to this any changes in the reference variable will be reflected in the original object.

How do I add a custom object in TreeSet?

Access and retrieval times are quite fast. To add the user-defined object into TreeSet, we need to implement a Comparable interface. An element that we want to add in TreeSet must be a comparable type. If we don't implement the Comparable interface then it will throw ClassCastException.


1 Answers

If you mean:

foo x = new foo();
x = 10; // This is meant to set x.bar

then no, you can't do that in Java. Good thing too, if you ask me... it would be horrible in terms of readability.

You also can't change it to allow:

foo x = 10;

as equivalent to:

foo x = new foo();
x.bar = 10; // Or x.setBar(10);
like image 128
Jon Skeet Avatar answered Nov 14 '22 21:11

Jon Skeet