import java.util.*;
import java.lang.*;
import java.io.*;

// this class allows setting i to anything and then fetching it
class A 
{
    private int i;
    void set_i(int _i)
    {
        i = _i;
    }
    int get_i()
    {
        return i;
    }
}

// this class also allows setting i to anything and then fetching it
class B 
{
    public int i;
}

// the main benefit of setters is that you can add logic to (for example)
// make sure that only allowed values are set
//
// but once you have a setter you must also have a getter ...
// see daydream about class D below
class C 
{
    private int i;
    void set_i(int i)
    {
        // note that since I called the parameter i, I use this.i for the member
        // instead of calling the parameter _i or anything else that is not i
        if(i < -10)
        {
            System.out.println("Warning, attempt to set i < -10, using -10");
            this.i = -10;
        }
        else if(i > 10)
        {
            System.out.println("Warning, attempt to set i > 10, using 10");
            this.i = 10;
        }
        else
            this.i = i;
    }
    int get_i()
    {
        return i;
    }

}

// Some languages support attributes that are public to get
// but private to set... Java does not as far as I know
//
// If Java had this you could write setters but not have to 
// write getters, if the situation called for it.
//
//class D 
//{
//    public int i {get; private set;}
//}

class Main {
    public static void main(String[] args) {
        var a = new A();
        var b = new B();
        var c = new C();
        a.set_i(10);
        b.i = 10;
        c.set_i(11);
        System.out.println("A: " + a.get_i());
        System.out.println("B: " + b.i);
        System.out.println("C: " + c.get_i());
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: