Object-oriented language base
Learn how to define classes and create objects
Summary:
Jeff · Friesen serves his Java journey series with Java-oriented features. In this issue, he introduced object-oriented programming and how to define classes and create objects from these classes. In addition, Friesen successfully fulfilled his promise for Javadoc research. See: "Java Documentation".
Nounted words, prompts and notices, homework, and other information on this column, see related "learning guidelines". (3500 words)
Looking back in the mid-1980s, I use the popular software development methodology - structured programming - to assist me write computer programs. Structured programming focuses on the data of the program and his functionality. As I found, typical difficulties separated from the function are difficult to maintain and understand - especially in large programs.
In the early 1990s, I learned a new development theory - object-oriented programming (OOP) .oop creates a very realistic software model with the real world in the source code and executable file code - like a car, bank account and Dog, etc. Structured programming focuses on the description of the entity to accommodate the limitations of the programming language; object-oriented programming focuses on creating a programming language to accommodate the description. For example, in a structured programming language, a vehicle is described as a set of functions (code segments) for start, braking, parking, acceleration, and the like. A set of independent variables are used to define the color of the car, the number, manufacturing, model, etc. of the door. You need to initialize these variables and call some functions to operate these variables - Wow, you have a car!
The OOP language regards the car as a whole constructed by his behavior - function, and the variable of the retainer - the data value. The result of integrating status values and behavior is initiated. You can simply create that object while initializing those variables. At any time, object-oriented programming has identified objects that use and call methods. Essentially, the object-oriented program is considered in a set of objects (eg, a car), rather than the functionality (such as: parking) and variables (such as the number of doors).
The technique of integrating status variables and behavior into the object is called "package". Package promotes information shield - By hiding status variables and behaviors make programs easier to maintain without entering their interior - this is one of the three basic concepts of OOP (I will explore the other two in the next article: Inheritance and polymorphism).
OOP has been widely used in developers for nearly 15 years, which is attributed to the popularity of C languages. However, because of its C language legacy features, C is not fully objective; you can write programs with C without using object-oriented features. Conversely, Java is fully object-to-object: Each Java program requires at least one class (an object-oriented feature). Moreover, Java's official language definition includes object-oriented terms (see "Resources").
This article will explore OOP in Java's perspective. I will start from the review class and objects; will also discuss the Javadoc to make the package, class, fields, methods and other documents. See Appendix: "Java Documentation".
Object-Oriented Language Basic Series:
One: How to define classes and create objects
2: Declaration, access field and method
Three: Structure: Build objects from other objects
4: Inheritance: Building a layer building
Five: base class
Six: Use interfaces to achieve more secure multiple inheritance
7: Learn more features of Java and adjust the framework in your class architecture
As the saying goes: the smart woman is difficult to be no rice. As a construction contractor needs to build a high-rise building according to the architect's basketmap, a running program must create the object based in advance before accessing a class. Definition class:
"Class" is the source code blueprint for the object. This blueprint defines the behavior and status variable of each object. Use the following syntax to declare a class:
['PUBLIC'] [('Abstract' | 'Final')] 'Class' Class_name
'{' // behavior and status variables define between '{' and '}'
'}'
Before the introduction class declaration, first detail the keywords: Class and the identifier behind it - the name of the class with class_name-class. The identifier cannot be a reserved word. For example: class Account describes a class that uses Account to do the name of this class. (Habular, class name uses uppercase.) Keyword public and / or abstract or final can appear freely before Class - but cannot have Abstract and Final at the same time, which will cause this class.
Contact the bag with the public keyword. Tag class_name as public to allow it to access all classes in all packets. And if it is not marked by the public, it can only be accessed to classes to class_name in the same name in the package. (I will explore the package in future articles.)
Remember the following rules when defining a public class: there can only be a public class in the source file. Moreover, the file name of this source file must be consistent with class_name. Such examples:
// myclass.javapublic class myclass {
}
Java requires the Myclass class to define in the source file of MyClass.java. Declare this class in other files - such as fred.java, or even myclass.java - is illegal. Use the correct identifier for class names, such as sensitive sensitive. (Such as MyClass, you must notice that M and C are capitalized, while others are lowercase.)
You can define non-PUBLIC classes in the source file named after any name, but the suffix of the file will still be .java. Such examples:
//Fred.java
Class myclass
{
}
The above example defines a non-public category: Myclass, and stores the implementation of the class in file Fred.java.
Use Keyword Abstract to define class_name as an abstract class. Objects cannot be created from abstract classes. (I will tell the concept of abstract classes in the next series.)
Use the keyword Final to define class_name as a final class. You can't inherit behavior and status variables from a Final class. (I will explore the concept of inheritance in the later series.) Keywords: public, abstract, and final can be declared in any order. For example: Public Abstract Class Fred, Final Public Fred, Abstract Fred, etc.
Each class has a text to define behavior (called methods) and member variables (called fields). The body begins: '{' ending in '}'. Although you may not define any methods and fields (such as the above MYCLASS) between {,}, there is no need to define methods and fields. Therefore, you will often define a field, method, or both in the class. (I will study in detail in the future.)
Class and Java programs
Each Java program has one or more classes. One of these classes is made as "start" class because it is the first class loaded by JVM. In fact, class files implements this startup class - a variable that implements behavior and hold status by providing code - loaded by JVM. As you can see in the previous Java 101 article, a Java application contains a boot class: main () method. Check out the list of CODEMO1 programs in the order to recall a simple program:
List one Codemo1.java
// codemo1.javaclass codemo1 {public static void main (string [] args) {system.out.println ("hello");}}
CodeMo1-Class / Object Demonstration 1 - is a simple Java program. The text of the CodeMo1 class is a separate method: main (). After you compile this code and use: Java Codemo1 commands, the JVM loads the boot class file - CodeMo1.class - and executes the byte code composed of main (). The result of the execution is to appear on the standard output device: Hello information.
Create an object
An object is an instance of a class. Use the following syntax to create an object:
'New' Constructor
"New" keyword, commonly referred to as a constructor, assigns memory space to an object and initialize the default value. The field value of the object is stored in memory. Since "New" is an operator, it takes an operational domain: builder, building a special method of the object. When "New" completes memory allocation and initialization, it calls the builder to complete the initialization of the object.
Listing 1 shows a simplest application. Although a list clearly shows the definition of a program necessary, there is no object created from this class. How will you create an object from the MAIN () method of the code and operate this object by accessing access to its field and calling your method? The list is given this answer:
List two. Codem2.java
// codemo2.java class codemo2 {int I = 3; public static void main (string [] args) {codemo2 obj1 = new codeMo2 ();
System.out.println ("obj1.i =" obj1.i); obj1.printhello (); codemo2 obj2 = new codemo2 (); obj1.i = 5; system.out.println ("obj1.i =" Obj1.i); obj1.printhello (); system.out.println ("obj2.i =" obj2.i); obj2.printhello ();}
Void PrintHello () {system.out.println ("Hello! i =" i "/ n");}}
Field definition statement: INT i = 3; define a integer (INT keyword) field: I, and initialize it to 3.
CodeMo2 Obj1 = New CodeMo2 (); a object is created from the CodeMo2 class. CodeMo2 Obj2 = New Codemo2 (); a second object is created. Since each object is an instance of a class, "class instance" is usually used as synonyms of the object.
CODEMO2 OBJ1 and CODEMO2 OBJ2 define variables with similar ways: Int Count or Double Balanceowing. Data Type Keywords: INT and Double Define the storage location named: Count and Balanceowing to store basic type data: integer and double precision floating point values. On the other hand, CODEMO2 defines a storage unit to store a value of a reference-or address-data type. In other words, since OBJ1 and OBJ2 have data types of CODEMO2 and CODEMO2 is a reference data type, any value assigned to OBJ1 and OBJ2 points to objects (or addresses) created by the CodeMo2 class.
The new operator of CodeMo2 calls CODEMO2 () to create an object. And slow! There is no declaration of CodeMo2 () in CODEMO2. What will happen? Please look for answers in this series of next article.
When the constructor creates an object, the constructor NEW returns the address of this object. In Listing 2, the first returned CODEMO2 object address is assigned to the OBJ1 variable; the second is OBJ2. Figure 1 depicts the objects referenced by each variable.
Figure 1. Two codemo2 objects and their respective reference variables
I imagine the object into a circle directed by one or more arrows. Each arrow clarifies an object reference, and the arrow starts with a rectangle of the stored object address.
Please see the call to the following method in Listing 2:
System.out.println ("Obj1.i =" Obj1.i);
Obj1.i mean? i is an integer variable that is initialized to 3. Objects created from CodeMo2 have the ability to have a copy of the variable (different values), so we must distinguish between multiple variables. Therefore, we must notify which copy of the program should be used. As the previous identifier I is an object referenced to OBJ1 (instead of OBJ2). Prefix usually uses a point operator. (I will introduce this knowledge in the next month's column)
Obj1.printhello (); calls the PrintHello () method, just in Obj1.i, the prefix of PrintHello () is Obj1. Since there is Obj2.PrintHello () in Listing 2;, so you may think there are two Copy of a PrintHello () method - each object has one. In fact, there is only one. Is it generated when the CodeMo2 file is loaded? Then, how the only printhello () copy is distinguishes this i is OBJ1 or OBJ2? The answer is Obj1. And Obj2. Prefix. The point operator in OBJ1 and Print Hello () is used to notify the printhello () method of i belong to OBJ1 (not OBJ2). This is also true for OBJ2. (I will introduce more methods in the next month)
Why don't you use OBJ1 or OBJ2 prefix in printhello ()? If you have doubts, please see the topic of the next month.
Now you have seen a little intrinsic nature of an object, and know how it is referenced, you may have doubts about the internal structure. Figure 2 shows a little structure.
Figure 2. Interior of a codemo2 object
Figure 2 shows two variables - Obj1 and Obj2 - reference two CODEMO2 objects. In fact, each variable is an address containing an object descriptor containing object information. The descriptor saves a memory address containing the object field and the code code of each CODEMO2 method. Take a closer look 2, Java seems to provide a pointer-pointing to the variable of other variable addresses. But in the language level, Java does not provide a pointer. Instead, Java uses "reference" - abstract object identifier. At the bottom layer, determine how to implement a reference by JVM. For example, a JVM may assign a number to a reference variable that points to the index of the object table, however another JVM may assign the memory address of the object to the reference variable. (In this example, the reference variable is basically a pointer to the object.) Because you don't know (nor do you need to know) how to assign a reference variable, you only need to know that the reference variable is a reference to the object - forget the pointer. !
Release object
C requires all objects that create stacks must be explicitly released - use C keywords: delete. However, Java undertakes the responsibility of the release of the created object. The JVM garbage collector operates in intermittent cycle to check if each object is referenced by at least one variable. If not, the garbage collector will destroy this object and release this memory at the same time.
Inside, JVM provides a reference counter for each object. When the configuration operation creates an object (for example: new codemo2 ();), and when the assignment is pointed to a reference variable (eg Codemo2 Obj1 = new code ();), the reference counter is initialized to one (In the background). Whenever this reference gives a variable of the additional data type, this counter adds one. When this counter is zero - Next, the garbage collector is running - JVM releases this object. Please see the example below:
// Create an object and assign him to myObjectReference.
Codemo2 myobjectReference = new codemo2 ();
// Internal reference counter is 1
// assign the reference of MyObjectReference to AnotherObjectReference.
Codemo2 annotherObjectReference = myObjectReference;
// Internal reference counter is 2
/ / Release one of them
MyObjectReference = NULL;
// Internal reference counter is 1
/ / Release another one
AnotherObjectReference = NULL;
// / / Internal reference counter is 0
// Here, the operation of the garbage collector is the object being released and recycled
About the Author:
Jeff Friesen uses complex computers for more than 20 years. He has a computer scientific degree and uses a variety of computer languages. And Jeff teaches the Java program in the college. He wrote an article for JavaWorld. He wrote a Java book for beginners - "Java 2 By Example" - and writes the second Java book based on its basis - "Special Edition uses Java 2 Platform" (QUE , 2001). Jeff has a "javajeff" nickname. For the recent work, please see his website:
http://www.javajeff.com
Resources:
Java documentation: