Java Classes And Objects

Java Classes

Classes in Java can be composed of both data as well as functions. Each and every method has something known as an access specifier. These‘are basically the keywords private, public, protected.
A private member can be accessed only from within the functions defined in the class. It can’t be accessed anywhere else. Having this restriction is necessary as it prevents misuse and unwanted manipulation of the state of the object from outside.
The default access specifier is always public.

class MyClass {
    private int alpha; // private access
    public int beta; // public access
    int gamma; // default access (essentially public)
    /* Methods to access alpha. It is OK for a member of a class to access a private member of the same class. */
 
    void setAlpha(int a) {
        alpha = a;
    }
 
    int getAlpha() {
        return alpha;
    }
}
 
class AccessDemo {
    public static void main(String args[]) {
        MyClass ob = new MyClass();
 
        /* Access to alpha is allowed only through its accessor methods. */
        ob.setAlpha(-99);
        System.out.println("ob.alpha is " + ob.getAlpha());
        // You cannot access alpha like this:
        // ob.alpha = 10; // Wrong! alpha is private!
        // These are OK because beta and gamma are public.
        ob.beta = 88;
        ob.gamma = 99;
    }
}

Difference between call by value and call by reference

Whenever an int or float or any such primitive data type is passed to the function it is always call by value.This basically means that when a function is called on for execution the parameters that are passed to it from the calling function are copied to the called functions i.e to the appropriate parameter. hence if we perform some mutation operations on these formal parameters they will not be reflected in the calling function.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License