10. Building a Java class
Building a Java class
So far, we have built Java applications that consist of a single class that contains everything needed to run the application; each class has included a main() method that controls the application. Most Java applications however consist of the controlling class that contains the main() method, plus other classes whose methods need to be called by the controlling class.
In fact, in
MyStringApp.java we saw the controlling class use methods from other classes. Think of Java objects as being 'black boxes' that contain a public interface (the methods that can be called), and a hidden implementation (the code and data that are required to make the methods work). Think of the
String class - you were given the names of some methods to call, but you couldn't see how these methods did what they do; all you could see was the result of calling the methods.
Different objects have different sets of methods. The
println() method can be called on the
System.out object, but not on the
String object, i.e. you can't make the following method call:
myString.println(); //illegal method call
This is because the
String objects belong to different classes.
println() is a method of the
PrintStream class; this method is not supported by the
String class. As we saw, the
String class supports a number of methods, any of which can be called on any
String object, because any object inherits all the methods of its class. Every object must belong to a class, and the class it belongs to defines the methods that the object has access to.
If we wish to build a class of our own, we must therefore define the class to contain all the instance variables and instance methods that any object instantiated by the class, must contain. Thereafter, every object that is an instance of our class will have all the methods of our class. It does not follow that every object will use all the methods it has access to, but it has the potential to use any or all of its methods at any time that it is called upon to do so.