Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"CONST" in java

Tags:

java

I have a question about "CONST" in java.

I want to know how to make like "const struct VAL &getVal()" in C-Language.

Here is sample code.

public class test {
   /* VAL is just structure-like class */
   class VAL {
    public int i;
   };
   private VAL  val;

   /* test class functions */
   test() {
    val = new VAL();
    val.i = 1;
   }

   VAL getVal() {
    return val;
   }

   /* main function */
   public static void main(String[] args) {
    test t = new test();
    VAL  t_val;

    t_val = t.getVal();

    t_val.i = 2; /* it should be error if t_val variable is a const */
    System.out.printf("%d %d\n", t.getVal().i, t_val.i);
   }
}

below is C sample code.

struct VAL
{
    int i;
};

const struct VAL &getVal() /* THIS IS WHAT I WANT */
{
    static VAL xxx;
    return xxx;
}

int main()
{
    const VAL &val = getVal();
    val.i = 0; /* error */

    VAL val2 = getVal();
    val2.i = 0; /* it's not an error, but it's ok because it cannot be changed xxx variable in getVal() either. */

    return 0;
}
like image 221
killinggun Avatar asked Sep 14 '26 00:09

killinggun


2 Answers

final keyword have similar semantics. You cannot change object's reference, however you can change the object itself if it is mutable. I'd suggest to google it and read more about it.

like image 95
Thresh Avatar answered Sep 16 '26 13:09

Thresh


you can't do the exact same thing like in C. Even though you use final keyword, it only prevent the modification of variable reference. t_val.i = 2 will be error if i is declared as final attribute.

like image 32
yogiebiz Avatar answered Sep 16 '26 13:09

yogiebiz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!