Declaring objects
By: aathishankaran Printer Friendly Format
Declaring objects
When you create a class, you are creating a new data type. You can use
this type to declare objects of that type. However, obtaining objects of a class
is a two-step process. First, you must declare a variable of the class type.
This variable does not define an object. Instead, it is simply a variable that
can refer to an object. Second, you must acquire an actual, physical copy of the
object and assign it to that variable. You can do this using the new operator.
The new operator dynamically allocates (that is, allocates at run time) memory
for an object and returns a reference to it. This reference is, more or less,
the address in memory of the object allocated by new. This reference is then
stored in the variable. Thus, in java, all class objects must be dynamically
allocated. Let’s look at the details of this procedure.
In the preceding sample programs, a line similar to the following is used
to declar an object of type Box.
Box mybox = new Box ();
This statement combines the two steps just described. It can be rewritten like this to show each step more clearly;
Box mybox;
mybox = new Box();
This first line declares mybox as a reference to an
object of type Box. After this line executes, mybox contains the value the value
null, which indicates that it does not yet point to an actual object. Any
attempt to use mybox at this point will result in a compile-time error. The next
line allocates an actual object and assigns a reference to it to mybox. After
the second line executes, you can use mybox as if it were Box object. But in
reality, mybox simply holds the
memory address of the actual Box object. The effect of these two lines of code
is depicted .
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Archived Comments
1. Huhhh.. copied from Complete reference ......:/
View Tutorial By: Tanzeel Mirza at 2013-04-06 04:48:59