Friday 26 February 2016

Variables and Class Types In JAVA

In Java, every class defines a new type (data type). A variable can be declared to be of this type and then hold instances of that class. A variable could, for example, be of type Button and hold an instance of the Button class, or of type SpreadSheetCell and hold a SpreadSheetCell object, just as it could be any of the simpler types, such as int or float, that represent numbers. The fact that variables have types and cannot simply hold any kind of object is another important feature of the language that ensures the safety and correctness of code. Ignoring the variables used inside the main() method for the moment, only one other variable is declared in our simple HelloJava example. It’s found in the declaration of the main() method itself:

 public static void main( String [] args ) {  
Just like functions in other languages, a method in Java declares a list of variables that it accepts as arguments or parameters, and it specifies the types of those variables. In this case, the main method is requiring that when it is invoked, it be passed a list of String objects in the variable named args. The String is the fundamental object representing text in Java. As we hinted earlier, Java uses the args parameter to pass any command-line arguments supplied to the Java virtual machine (VM) into your application. (We don’t use them here.) Up to this point, we have loosely referred to variables as holding objects. In reality, variables that have class types don’t so much contain objects as point to them. Classtype variables are references to objects. A reference is a pointer to or a handle for an object. If you declare a class-type variable without assigning it an object, it doesn’t point to anything. It’s assigned the default value of null, meaning “no value.” If you try to use a variable with a null value as if it were pointing to a real object, a runtime error, NullPointerException, occurs. Of course, object references have to come from somewhere. In our example, we created two objects using the new operator. We’ll examine object creation in more detail a little later in the chapter.

0 comments:

Post a Comment