Since all Java program activity occurs within a class, we have been using classes since the start of this book. Of course, only extremely simple classes have been used, and we have not taken advantage of the majority of their features. As you will see, classes are substantially more powerful than the limited ones presented so far. Let’s begin by reviewing the basics. A class is a template that defines the form of an object. It specifies both the data and the code that will operate on that data .Java uses a class specification to construct objects. Objects are in stances of a class. Thus, a class is essentially a set of plans that specify how to build an object. It is important to be clear on one issue: a class is a logical abstraction. It is not until an object of that class has been created that a physical representation of that class exists in memory. One other point: recall that the methods and variables that constitute a class are called members of the class. The data members are also referred to a sin stance variables.
Friday, December 14, 2018
Class Fundamentals
December 14, 2018
No comments
When you define a class, you declare its exact form and nature. You do this by specifying the instance variables that it contains and the methods that operate on them. Although very simple classes might contain only methods or only instance variables,most real-world classes contain both. A class is created by using the key word class. The general form of a class definition is shown here:
class class name
{
// declare instance variables t
ypevar1;
typevar2;
// ...
typevarN;
// declare methods type method 1
(parameters)
{
// body of method
}
type
method2
(parameters)
{
//
body of method
}
// ... type method N
(parameters)
{
// body of method
}
}
Although there is no syntactic rule that enforces it, a well-designed class should define one and only one logical entity. For example, a class that stores names and telephone numbers will not normally also store information about the stock market, average rain fall, sunspot cycles, or other unrelated information. The point here is that a well-designed class groups logically connected information. Putting unrelated information into the same class will quickly destructure your code! Up to this point, the classes that we have been using have only had one method:main( ). Soon you will see how to create others. However, notice that the general form of a class does not specify a main( )method. A main( )method is required only if that class is the starting point for your program. Also, applets don’t require a main( ).
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment