Java: using classes, part 0
To an academic, Java’s elegance is delicious. The tutor begins coverage of how to use classes.
In Java, a class is basically a more complex evolution of a type. A class can house many variables, but also contain its own functions, which Java calls methods. A programmer can use predefined classes provided by Java, by rarely (in my experience) can a problem be solved using predefined classes alone.
A programmer might find themselves in a situation where they need a certain method that a predefined class already contains. In my experience, such is often the case: you want access to a certain method, so you create an instance of the class that contains it. Then you send your arguments to its method whose functionality you want.
There are five points to be aware of in this context:
1) A method is recognizable because it’s followed by brackets: eg, method1()
2) Java is case sensitive; to it, T1 and t1 are not related at all.
3) Convention says that the title of a Java class begins with a capital letter, but an instance of the class begins with lower case. Furthermore, a method begins with lower case.
4) An instance of a class is an embodiment of its definition. An instance can be created with the new operator.
5) Generally, you need an instance of a class in order to access its methods.
Let’s imagine, for instance, you want the method m1() contained in class T1. What you’ll likely do is set up an instance of T1, here calling it myT1:
T1 myT1 = new T1(); //Creating an instance is seen as a method.
Let’s imagine you want to send the arguments arg1 and arg2 to method m1() in myT1, then store the result in the variable res. What follows shows how you might do so. Note that to access the method m1() in myT1, you do so using the period . operator:
res=myT1.m1(arg1,arg2);// the . tells Java m1() is from myT1
In coming posts I’ll much more discuss using classes and writing new ones.
HTH:)
Source:
Niemeyer, Patrick and Jonathan Knudsen. Learning Java. Sebastopol, CA: O’Reilly Media, Inc., 2005.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.