Java Reference
In-Depth Information
In the preceding chapters, you learned how to use various classes and their methods to
manipulate data. Java does not provide all the classes that you will ever need, so it permits
you to design and implement your own classes. Therefore, you must learn how to create
your own classes. This chapter discusses how to create classes and objects of those classes.
Classes and Objects
Recall, from Chapter 1, that the first step in problem-solving using object-oriented
design (OOD) is to identify the components called classes and objects. An object of a class
has both data and operations that can be performed on that data. The mechanism in Java
that allows you to combine data and operations on the data in a single unit is called a class.
(Combining data and operations on the data is called encapsulation—the first principle of
OOD.) Now that you know how to store and manipulate data in computer memory and
how to construct your own methods, you are ready to learn how classes and objects are
constructed.
In Chapter 3, we described the class String and illustrated how to use the various
String methods. Using the class String , you can create various String objects,
each storing a different string, and using the methods of the class String ,eachobject
can manipulate its string. The class String allows us to group data, which are strings,
and operations on that data in a convenient way. We can use the class String in any
Java program that requires the manipulation of strings, without re-creating it for a
specific program. In fact, the Java programming language provides a wealth of pre-
defined classes that can be effectively used in any program. For example, in Chapter 7
we discussed how to use the class es Math and Character , and in Chapter 6, we used
various classes, such as JFrame , JText ,and JLabel , to create GUI programs.
However, Java does not provide all the classes that we will ever need as it does
not know the specific needs of a programmer. Therefore, we must learn how to
create our own classes.
Before discussing how to design your own classes, let's first learn how the class String
looks. In skeleton form the class String has the following form:
public final class String
{
//variables to store a string
...
public int compareTo(String anotherString)
{
//code to compare two strings
}
public String concat(String str)
{
//code to join two strings
}
 
Search WWH ::




Custom Search