13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.2 Fundamental Language Elements59Example 3.6 Using simple class// declare a reference to <strong>on</strong>e:PairInt twovals;// now create <strong>on</strong>e:twovals = new PairInt(5, 4);// we can also declare and create in <strong>on</strong>e step:PairInt twothers = new PairInt(7, 11);time to run the program, its various classes are loaded as needed. We’ll discussgrouping classes together and how Java locates them in Secti<strong>on</strong> 3.3.1.In Java, each source file c<strong>on</strong>tains <strong>on</strong>e class and the file is named after thatclass. It is possible to define inner classes located inside another class definiti<strong>on</strong>and thus inside its file, but that introduces other complexities that we wish toavoid discussing at this point. Most importantly, an inner class has access toeven the private members of the enclosing class. (Read more about inner classesin any of the Java books that we recommend at the end of this chapter.)For each of the class methods, class data declarati<strong>on</strong>s, and the class itself,Java has syntax to limit the scope, or visibility, of those pieces. The examplesabove didn’t include those keywords—that is, they took the default values.Usually you’ll want to specify something. See Secti<strong>on</strong> 3.4.1.3.2.2.1 Objects as ReferencesSo far we have not explained something important about object type variables.These variables can all be thought of as pointers or references to an object.When you declare a variable of an object type, what you are declaring is a variablethat is capable of referring to an object of that type. When declared, it doesnot point at anything. It has a value of null and any attempt to use it will resultin a null pointer excepti<strong>on</strong> (more <strong>on</strong> those later).Before an object variable might be used, it must be made to refer to aninstance of an object. This is d<strong>on</strong>e by assignment. You can assign an existingobject, or you can use the new operator.Any new class will have a c<strong>on</strong>structor, that is, a method whose name is thename of the class. There can be many different c<strong>on</strong>structors for the same class,

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!