“Object” vs “Object Variable” in Java?

后端 未结 6 1565
春和景丽
春和景丽 2021-02-01 19:01

I am teaching myself Java, and one of the review exercises in my book asks for the difference between an \"object\" and an \"object variable.\"

I know what an object is

6条回答
  •  日久生厌
    2021-02-01 19:32

    tl;dr;fmoe

    I came across the same question in a review exercise found within Cay Horstmann, Big Java, Early Objects (John Wiley & Sons, 2013), 73.

    Cay defines an object variable as a variable (whose type is a class) which stores a reference to the memory location of an object.

        Rectangle box = new Rectangle();
    
    • box is the object variable which stores a reference to the newly instantiated Rectangle object's memory location.

    Multiple object variables can exist which store the same reference to an object's memory location.

        Rectangle box = new Rectangle(5,10,20,30);
        Rectangle box2 = box;
    

    Calling a mutator/mutagenic method (modifies the object on which the method is invoked) on either object variable mutates (modifies) the object since the object variables reference the same object's memory location

        box2.translate(15, 25); 
        System.out.println(box.getY()); // 35.0
        System.out.println(box2.getY()); // 35.0
    

    This gets a bit confusing if you compare Cay's definition with the information from The Java Tutorials, and numerous other sources, but I believe this is the answer to your question when placed within the context of Cay's book(s).

    I prefer this perspective => An object's memory location is stored in the object reference (object variable per Cay). When I invoke a method on an object, I specify the object reference followed by the dot (.) operator, followed by the method name.

        objectReference.method();
    

    If the public interface of a class allows access to one or more of it's instantiated object's fields (AKA instance variables, object variables, class member variables, properties, or attributes... depending on programming language and documentation) then I can access it by specifying the object reference, followed by the dot (.) operator, followed by the field name

        objectReference.fieldName;
    

    Why do I prefer this? I'm not a fan of using variable as a noun too many times; overloaded semantics boggle my simple mind.

提交回复
热议问题