Java Basics (iii) objects and classes

Source: Internet
Author: User
Tags modifier value of pi

1. Class Concept: A class is a template or blueprint for constructing an object. The process of constructing an object from a class is called creating an instance of the class.

2. Encapsulation Concept: encapsulation (sometimes referred to as data hiding) is an important concept related to objects. The data in the object is called the instance domain, and the process of manipulating the data is called a method. There is a specific set of instance domain values for each particular class instance (object). Several of these values are the current state of this object. Whenever a message is sent to an object, its state is likely to change. The key to implementing encapsulation is that the methods in the class are absolutely not allowed to access the instance domains of other classes directly. A program interacts with object data only through the methods of the object. Encapsulation gives the object a "black box" feature, which is the key to improving reusability and reliability. This means that a class can completely change the way data is stored, as long as the same method is still used to manipulate the data, other objects will not know or mind the changes that have occurred.

3. Three main features of an object:

    • (1) Behavior--what actions can be applied to an object, or what methods can be applied to an object
    • (2) State-How the object responds when those methods are applied
    • (3) Identification--How to identify different objects with the same behavior and state

4. Relationships between classes:

    • Dependency (USES-A): If a method of one class manipulates an object of another class, it is said that one class depends on the other class.
    • Aggregation (HAS-A): An aggregation relationship means that an object of Class A contains an object of Class B.
    • Inheritance (IS-A): If Class A extends Class B, class

5. Advantages of Encapsulation

If you need to get or set the value of an instance field, you should provide the following three things:

    • A Private data field
    • A public domain accessor method (get ())
    • A public domain Change method (set ())

The advantage of this is that once the private data domain is set up in the constructor, the private domain can only be accessed through the public domain accessor method, and the private domain can only be modified through the public domain modifier. Once this domain value has an error, it is only possible to debug this method, and if the domain is public, a troublemaker who destroys the domain may appear anywhere.

6. Private methods

If you want to divide a calculation code into separate auxiliary parts, usually these auxiliary methods should not be part of the public interface because they are often very close to the current implementation mechanism, or require a special protocol and a special invocation order. It is best to design such a method as private, because the private method can only be called by the method of the current class, and the outer class cannot be called.

For private methods, you do not have to preserve the original method if you use other methods to implement the appropriate operation. As long as the method is private, the designer of the class can be assured that it will not be invoked by other classes of external operations and can be deleted. If the method is public, it cannot be deleted because the other code is likely to rely on it.

7.final instance Domain

When you define an instance field as final, you must initialize such a domain when you construct the object. That is, you must ensure that the value of the field is set after each constructor is executed, and that it cannot be modified in subsequent operations.

8. Static domain

If you define a domain as static, there is only one such domain in each class, and each object has its own copy for all instance domains.

class employee{
Private Static int NextID = 1; privateint ID;}

For example, each employee object has its own ID field, but all instances of this class share a NextID domain. That is, if there are 1000 employee class objects, there are 1000 instance domain IDs. However, there is only one static domain NextID. Even if there is no Employee object, the static domain NextID also exists. It belongs to a class and does not belong to any independent object.

  9. Static constants

 Public class math{publicstaticfinaldouble PI = 3.14159265358979323846; ...}

If the keyword static is omitted, Pi becomes an instance field of the math class. You need to access pi through the object of the math class. And every math object has its own copy. If STATIC,PI is used, it belongs to the math class, which means that any call to the value of pi in the math class is unique and only one. Nor can it be accessed by an object of the math class. Also, as mentioned earlier, it is better to design the instance domain as private, but the public constant (final domain) is not a problem because the PI is declared final as immutable, so it is not allowed to assign another value to pi.

10. Static methods

A static method is a method that cannot be manipulated against an object. Objects of any class are not required when using static methods.

 Public Static int Getnextid () {      return  nextid;  }

The static method of the employee class cannot access the ID instance domain because it cannot manipulate the object. However, a static method can access a static domain in its own class.

This method can be called by the class name. If Static is omitted, this method needs to be called through a reference to the Employee class object.

int n = employee.getnextid ();

The static method is used in the following two cases:

    • A method does not require access to the object state, and its required parameters are provided through the display parameters. (For example, Math.pow (X,a))
    • A method only needs to access the static domain of the class (for example, Employee.getnextid ())

11. Static code block

+    //  static initialization block                 : (+)       //  set NextID to 0 to 9999 random number       NextID = Generator.nextint (10000); +    }

Before a class is constructed, a static initialization block can be used if the code that initializes the static domain of the class is more complex. Place the initialization code in a block and tag the keyword static.

This will initialize the static domain at the first time the class is loaded. As with instance domains, all static initialization code blocks are executed in the order in which the class is defined.

12. Package Scope

    • Classes, methods, or constants that are marked as public can be used by any class.
    • Classes, methods, or constants that are marked private can only be used by the class in which they are defined.
    • If public or private is not specified, the class, method, or constant can be accessed by all methods in the same package.

Class Design Tips

    • Be sure to keep your data private

Never break encapsulation. Sometimes you need to write an accessor or modifier method, but it is best to keep the instance domain private. the representation of the data is likely to change, but the way they are used does not change very often. when data remains private, changes in their representation do not affect the consumer of the class, even if the bug is easily detected.

    • Be sure to initialize the data

  It is best not to rely on the default values of the system, but to initialize all the data in the display. the specific initialization can be either to provide a default value or to set a default value in all constructors.

    • Do not use too many basic types in a class

The use of other classes instead of multiple related basic types makes the classes easier to understand and easier to modify.

For example, the customer class includes many instance fields, with instance domains street,city and state, which can be replaced with a new class of address, which reduces the number of instance fields in the Customer class.

    • Not all domains require a separate domain accessor and domain modifier

If there are domains that you do not want others to access or modify, do not set up domain accessors or domain modifiers. To be set according to the actual situation and needs.

    • Decompose a class with too many responsibilities

One scenario is to break down classes that implement many functions into several different classes that share all the responsibilities of the original class.

    • Class names and method names should be able to reflect their responsibilities.
    • Preferential use of immutable classes

The problem with changing objects is that if multiple threads try to update an object at the same time, concurrent changes occur. The result is unpredictable. If the class is immutable, it is safe to share its objects among multiple threads.

  

          

Java Basics (iii) objects and classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.