Search in This Blog

Saturday, 18 November 2017

Java objects Basis

         Object :

The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
A class instance is explicitly created by a class instance creation expression.
An array is explicitly created by an array creation expression.
Other expressions may implicitly create a class instance  or an array.

 Object Creation
class Point {
    int x, y;
    Point() { System.out.println("default"); }
    Point(int x, int y) { this.x = x; this.y = y; }

    /* A Point instance is explicitly created at 
       class initialization time: */
    static Point origin = new Point(0,0);

    /* A String can be implicitly created 
       by a + operator: */
    public String toString() { return "(" + x + "," + y + ")"; }
}

class Test {
    public static void main(String[] args) {
        /* A Point is explicitly created
           using newInstance: */
        Point p = null;
        try {
            p = (Point)Class.forName("Point").newInstance();
        } catch (Exception e) {
            System.out.println(e);
        }

        /* An array is implicitly created 
           by an array constructor: */
        Point a[] = { new Point(0,0), new Point(1,1) };

        /* Strings are implicitly created 
           by + operators: */
        System.out.println("p: " + p);
        System.out.println("a: { " + a[0] + ", " + a[1] + " }");
    
        /* An array is explicitly created
           by an array creation expression: */
        String sa[] = new String[2];
        sa[0] = "he"; sa[1] = "llo";
        System.out.println(sa[0] + sa[1]);
    }
}
This program produces the output:
default
p: (0,0)
a: { (0,0), (1,1) }
hello

The operators on references to objects are:
  • Field access, using either a qualified name or a field access expression 
  • Method invocation
  • The cast operator 
  • The string concatenation operator + , which, when given a String operand and a reference, will convert the reference to a String by invoking the to String method of the referenced object (using "null" if either the reference or the result of to String is a null reference), and then will produce a newly created String that is the concatenation of the two strings
  • The instanceof operator
  • The reference equality operators == and !=
  • The conditional operator ?
There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.

No comments:

Post a Comment