Java - Object (instance of a class)

> Procedural Languages > Java

1 - About

An object:

  • stores its state in fields
  • and exposes its behaviour through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.

From a class, you can create several object (instance of a class) with different state but the same behaviours. A class provides the blueprint for objects; you create an object from a class. When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.

A typical Java program creates many objects, which as you know, interact by invoking methods.

The phrase “instantiating a class” means the same thing as “creating an object.” When you create an object, you are creating an “instance” of a class, therefore “instantiating” a class.

Advertising

3 - Benefits

Bundling code into individual software objects provides a number of benefits, including:

  • 1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  • 2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
  • 3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  • 4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

4 - Data Type

Every object is either:

datatype

For every type of object, the Java virtual machine instantiates an immutable instance of java.lang.Class.

5 - How to

5.1 - (Create|Instantiate) an object

Each of the following statements creates an object and assigns it to a variable:

Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

Each of these statements has three parts (discussed in detail below):

  • 1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
  • 2. Instantiation: The new keyword is a Java operator that creates the object.
  • 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Advertising

5.1.1 - The new operator

5.1.1.1 - Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

The phrase “instantiating a class” means the same thing as “creating an object.” When you create an object, you are creating an “instance” of a class, therefore “instantiating” a class.

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.

5.1.1.2 - The return value

The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:

int height = new Rectangle().height;

5.1.2 - Class

Interfaces and abstract classes can never be instantiated. You must always instantiate a concrete class but you can assign the resulting object to an interface.

Example where:

with this hierarchy

InterfaceFoo < AbstractFoo < ImplementationFoo
// Valid
InterfaceFoo foo= new ImplementationFoo ();
AbstractFoo foo = new ImplementationFoo ();
// Invalid
InterfaceFoo foo = new InterfaceFoo();
InterfaceFoo foo = new AbstractFoo();
AbstractFoo foo = new AbstractFoo();
Advertising

5.1.3 - Dynamic

For a class with a constructor without argument otherwise others reflection method must be used

Foo foo;
String fooClassName = getFooImplClass();
InterfaceFoo  foo =  (InterfaceFoo) Class.forName(fooClassName).newInstance();

5.1.4 - Builder Pattern

5.2 - Get

5.2.1 - instanceof (Type)

Object o = new Integer("3");
 
if (o instanceof Integer)) {
        System.out.println("This is an integer");
}

5.3 - Drop an object

Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone.

The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

An object is drop:

  • by the garbage collection when there are no more references to that object.
  • explicitly by setting the variable to the special value null.

Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.

5.4 - Equality

  • The == operator verify that they are the same object. (Ie object id not the same value !)
  • whereas the equals method verify that you have the same logical object (ie the same passport Id for instance)

See Java - equals method

6 - Documentation / Reference

lang/java/object.txt · Last modified: 2017/09/20 22:34 by gerardnico