The Secret to Understanding Objects in Java

Cloudage
Java is a heavily object-oriented programming language, and uses objects to get things done. In this article we'll look at what an object really is, and how to create a new object, or instance.

In Java you can do almost anything with object, and Java wouldn't be object-oriented if we couldn't. When you define a set of classes, you are actually creating templates that are used to create objects. The objects that you create are instances of these classes, and you create them using the new operator.

When you use the new keyword, you instantiate an object. Every time you use the new keyword, a special method is called, the constructor. The constructor sets up the initial state of the object, and creates other objects that the object might need. You can also define other methods to change the attributes of an object, and then call these methods for the code.

The new operator is used with the name of the class you want to create an instance of, followed by parentheses. The arguments inside the parentheses are the constructor, or the initial state of the object, and if there's no need for it, it can be left out.

When you use the new operator, memory is allocated for the new instance of the given class, and the constructor is called. You can also have multiple constructor definitions in a class, and they can each have a different number or type of arguments. It all depends on how many constructors you need to implement the behavior of the class.

On a side note, we strive to keep our programs as small as possible, so can we have an opposite of the new operator, an operator that destroys the object when it's no longer needed?

The answer is that Java has an automatic memory management, and you do not need to deallocate the memory after it has finished. In 99 % of the cases Java itself will be able to determine that the object is no longer needed, typically when there are no more live references to it, and Java uses a process called garbage collection to reclaim the memory from that object.

To put it another way, the smallest things in Java, the primitive data types (byte, short, int etc.) can in many ways be handled like objects. They can be assigned to variables, and be passed in and out of methods. The difference is that the operations that work only on objects, will not work on these primitive types. Objects are instances of classes and are usually much more complex than the data types above.

Published by Cloudage

I am a student studying and tutoring in math, chemistry and physics.  View profile

  • Classes are mere templates, and objects are instances of these.
  • The constructor defines the initial state.
  • Java tutorials online is a great way to learn!

To comment, please sign in to your Yahoo! account, or sign up for a new account.