Java Fundamentals: Object-oriented

Source: Internet
Author: User

1. Class

Java classes, including properties, methods, constructors, initialization blocks, local variables, internal classes and other members, each member can be decorated by various modifiers. A member that is actually decorated with the static modifier, called a static member (a class member), and not a member of the static modifier, is called an instance member.

1) Static members (class members)

Static members belong to the entire class and do not belong to a single object. Class members are static properties that are modified by the static keyword, static blocks, static methods, static inner classes, and so on.

for the static keyword, there is a very important rule: class members ( Static properties, static initialization blocks , static methods, static internal classes ) cannot access instance members ( Instance properties, instance initialization block , instance method, instance inner class ). Because a class member belongs to a class, the scope of the class member is larger than the scope of the instance member, it is entirely possible that the class member has been initialized, but the instance member has not yet been initialized, and allowing the class member to access the instance member will cause a lot of errors.

(1) Static properties

Static properties belong to the entire class. When the system first prepares to use the class, the system allocates memory space in the JVM's method area for the static property, and the static property begins to take effect until the class is unloaded, and the memory occupied by the static property of the class is reclaimed by the system's garbage collection mechanism (major GC in the Perm area). The existence of a static property is almost identical to the life span of the class. When the class initialization is complete, the static property is initialized.

Static properties can be accessed either through the class or through the object of the class. However, when you access a static property through the object of the class, you are not actually accessing the property owned by the object, because when the system creates an object of that class, the system no longer allocates memory for that static property, nor does it initialize the static property again, that is, the object does not have a static property of the corresponding class at all. Accessing a static property through an object is only an illusion, and the static property of the class is still accessible through the object. It can be understood that when a static property is accessed through an object, the system transforms the underlying to access the static member through the class.

Ps:c# does not allow access to static properties through objects, objects can only access instance properties, and static properties must be accessed through classes.

Because objects do not actually hold static properties, static properties are held by the class, and when all objects of the same class access a static property, the static properties that the class holds are actually accessed. As a result, all instances of the same class can be seen sharing the same block of memory (static properties are stored in the class information in the JVM's method area).

(2) static method

Static methods are also classes, and typically call class methods directly using classes as callers, but you can also invoke class methods through the class's objects. Similar to static properties, even if you use an object to invoke a method, the effect is exactly the same as calling a class method with a class.

When an instance is used to access a class member, it is actually still delegated to the class to access the class member, so even if an instance is null, it can access the class member of the class to which it belongs.

For example:

The package Com.demo3;public class Nullaccessstatic {static void Test () {System.out.println ("static method of static Adornment");} public static void Main (string[] args) {//define a nullaccessstatic variable with a value of nullnullaccessstatic nas = null;// The null object calls the static method of the owning class Nas.test ();}}

Output Result:

static method of Static modification

PS: If a null object accesses an instance member (including members and methods), a NullPointerException exception is thrown.

(3) Static initialization block

Static initialization blocks are also one of the class members, where static initialization blocks are used to perform class initialization actions, and static initialization blocks of the class are called to initialize the class during the initialization phase of the class. Once the initialization of the class is complete, the static initialization block will never get the chance to execute.

2) Instance members

The fundamental way to create an object is the constructor, which invokes the constructor of a class with the new keyword to create an instance of the class. Most of the time, defining a class is to repeat the creation of instances of that class, with multiple instances of the same class having the same characteristics, while classes define common characteristics of multiple instances. from a certain point of view, a class defines the characteristics of multiple instances, so a class is not a concrete existence, and an instance is a concrete one.

(1) object, reference, pointer

There is this line of code:

Person P=new person ();

This line of code creates a person instance, also called a Person object, which is assigned to the P variable. This line of code actually produces two things: a P variable, and a person instance. The person instance is stored in the heap memory area of the JVM to store the actual data information of the person, and the P variable is actually a reference, which is stored in the JVM's thread stack memory, pointing to the actual person instance.

In fact, the reference in Java is a pointer to C, but the Java language encapsulates the pointer to avoid tedious pointer manipulation by the developer. when an instance is created successfully, this instance is saved in heap memory, the Java program does not allow direct access to the objects in the heap memory, only the object can be manipulated by reference to that object, that is, both arrays and objects can only be accessed by reference. In Java thread stack memory, objects are not stored and only basic data types and references are stored.

If the object in the heap memory does not have any variables pointing to the object, then the program will no longer be able to access the object, and the object becomes garbage, and the garbage collection mechanism in Java reclaims the object and frees the memory space used by the object.

(2) This keyword

Java provides a This keyword, the This keyword can only appear in instance blocks and instance methods, and static decorated class Members cannot use the This keyword, so the Java syntax stipulates that static members cannot access non-static members directly. The This keyword always points to the object that called the method. the most important role of the This keyword is to allow a method in the class to access another method or property in the class instance.

A member of the Java runtime object directly calls another member, which can omit the this prefix. Omitting this prefix is only an illusion, although this is omitted, but this is still present.

For an instance method, you can interpret it as Python, as follows: In the formal parameter list of an instance method, an this parameter is hidden by default.

In fact, the inside of the JVM is implemented by the default rules of the stack frame.

Example:

Package Com.demo3;public class Demo {static String staticname; String instancename;public static void SayHello () {System.out.println ("static SayHello:" + staticname);} public void Sayworld () {System.out.println ("This sayworld:" + This.instancename);}}

Anti-compilation via JAVAP:

Javap-c Demo.class

Anti-compilation results:

By contrast, it is found that obtaining the "staticname" static property, using the getstatic directive,refers to loading the static property of the JVM's method area to the top of the stack frame operating area ; This.instancename "directives use" aload_0 "and GetField directives," aload_0 "instructions are used to load the first variable of the local variable area of the stack frame to the top of the stack frame operating area,"GetField" The command is used to eject the top reference of the action area stack and get the property of the instance in the heap that the reference points to, and finally press the property into the top of the operation area stack.

Based on the characteristics of the local variable area of the JVM stack frame: The first variable of the local variable area corresponding to the stack frame is the instance's own reference, this; the first variable in the local variable area corresponding to the stack frame is not this, and the other local variables.

Therefore, where this is used, at compile time, it is replaced by the aload_0 instruction.

(3) Super keyword

Example:

Package Com.demo3;public class Demo {String instancename;public void SayHello () {System.out.println ("Demo.sayhello");}}
Package Com.demo3;public class Demo2 extends Demo {String instancename;public void Sayworld () {System.out.println ( This.instancename); This.sayhello ();} public void Saysun () {System.out.println (super.instancename); Super.sayhello ();}}

To decompile a demo2.class file with JAVAP:

Javap-c Demo2.class

Get method anti-compile directives:

According to bytecode instructions:

At compile time, the This keyword is substituted by the aload_0 instruction, and the super is replaced by the ALOAD_0 directive, but the property after super is specified as the parent class property, and the method after super is specified as the parent class method and is invoked with the invokespecial directive.

The JVM provides bytecode instructions for 4 method calls:

    • Invokestatic: Calling a static method

    • Invokespecial: Invoking instance constructors <init> methods, private methods, and parent class methods

    • Invokevirtual: Calling all virtual methods

    • Invokeinterface: Invokes an interface method that, at run time, determines an object that implements this interface.

As long as the methods that can be called by invokestatic and Invokespecial are statically connected. as long as the methods that can be called by invokevirtual and Invokeinterface are dynamic connections. in addition to static methods, instance constructors, private methods, and parent methods, other methods are called virtual methods.

Java non-virtual methods in addition to invokestatic and invokespecial, there is a final modification of the method, because the method cannot be overwritten, the final modified method is called with the invokevirtual directive.

The main differences between Invokespecial and invokevirtual are:

    • invokespecial static binding; invokevirtual Dynamic binding

    • Invokespecial invokes instance constructors <init> methods, private methods and parent-class methods, and invokevirtual primarily calls instance methods other than static methods, instance constructors, private methods, and parent class methods.

    • At run time, the Invokespecial selection method is based on the type of the reference, not the actual type to which the object belongs. Invokevirtual , however, selects the actual type to which the object belongs.

The GetField directive, like Invokespecial, is also a reference-based type, not the actual type of the object.

In summary, in the use of super, at compile time, are replaced by the aload_0 instruction, and GetField get the parent class property, Invokespecial call the parent class method, where this is used, at compile time, are replaced by the aload_0 instruction, The GetField directive obtains this class of properties, Invokevirtual calls this class of methods.

(4) method parameter passing

As we all know: the transfer of function parameters in C is: value passing, address passing, and reference passing three kinds of forms. In Java, however, there is only one way to pass the parameters of a method: value passing. A value pass is a copy (replica) of the actual parameter value passed in to the method, and the parameter itself is unaffected.

To illustrate this issue, first make two points clear:

    • 1. References in Java are a data type, with the same status as the base type int, and so on.

    • 2. The program runs always in the JVM stack, so when parameters are passed, there is only a problem passing the base type and object references. The object itself is not passed directly.

In the run JVM stack, the basic type and the reference are handled the same, all of which are value-passing. If it is a quoted method call, it can be understood as a "reference value" of the call, that is, "reference value" was made a copy, and then assigned to the parameter, the reference processing is exactly the same as the basic type. However, when the invoked method is entered, the referenced value passed is interpreted (or found) by the program to the object in the JVM heap, which corresponds to the actual object. If you modify at this point, you modify the reference object instead of the reference itself, which is: the data in the JVM heap is modified. So this is a change that can be maintained.

(5) ToString () method

The ToString method is a very special method that comes from the object class, which is a "self-describing" method, which is typically used to implement a function that, when the programmer prints the object directly, the system will output the object's "self-describing" information to tell the outside world what state information the object has.

The ToString method provided by the object class always returns the "class name [e-mail Protected]+hashcode" Value of the implementation class of the objects, and this return value does not really implement the "self-describing" function, so if a user needs a custom class to implement a "self-describing" function, You must override the ToString () method of the object class.

(6) equals and = =

For basic types, = = is a comparison of two values, and for reference types, = = is used to determine whether two reference variables point to the same object.

The Equals method is a method of the object class, and the Equals function is primarily used to define the comparison logic for object equality. The default is to compare two objects in the heap, whether the same pointer (the same object), that is: return (this = = obj); The basic types of wrapper classes, such as Integer, float, and the string class, are overridden by the Equals method. They no longer compare the object's heap address, but rather compare the object's content.

The Equals method is associated with the method Hashcode () method of object. This is mainly designed to the hash table (hash list) of the relevant knowledge.

Given table M, there is a function f (key), for any given keyword value key, after substituting the function if you can get a record containing the key (key) in the table address p, is called Table M is a hash (hash) table, function f (key) is a hash (hash) function, P is the hash value of the keyword key.

The comparison logic involved in equals is key, and the function f () is the Hashcode () method, and P is the return value of the Hashcode () method. So according to the characteristics of the hash table can be obtained:

    • When two objects call the Equals function and return true, it means that the keyword key is the same, and the return value of the Hashcode function should be the same.

    • When two objects call the Equals function, returning false means that the keyword key is not the same, then the return value of the Hashcode function may be the same.

Therefore, when overriding the Equals function, you should also change the corresponding Hashcode method to accommodate the feature.

3) Local Variables

The scope of the formal parameter is the entire method that is called by the method when the value is specified. is mainly allocated in the stack frame of the online stacks. At the end of the method, it is automatically destroyed. The parameter is best not to be re-assigned during the execution of the method. Because the formal parameter represents the actual entry parameter, it is best not to easily change the entry parameters, which can be decorated with the final keyword.

Method local variables and code blocks the scope of the local variables is the variable definition when the nearest bracket {} code blocks. For example:

Package Com.demo3;public class Test {public static void main (string[] args) {int a = 1;{ int b = 1;} int[] array = new int[] {1, 2, 3, 4, 5};for (int i = 0; i < Array.Length; i++) {System.out.println (array[i]);}}

The scope of a is the entire method, the scope of B is {int b=1;}, and the scope of I is the loop body of the for.

Java allows local variables and member variables with the same name, if the local variables in the method have the same name as the member variables, the local variables will overwrite the member variables , if you need to refer to the overridden member variable in the method, you can use this (for the instance property) or the class name (for static properties) Restrict access to member variables as callers. However, most of the time, you should try to avoid local variables and member variables with the same name.

4) Initialization


Cond

Java Fundamentals: Object-oriented

Related Article

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.