Java Multi-State summary

Source: Internet
Author: User

/*
Polymorphic: Polymorphism refers to the existence of multiple states of a thing (multiple forms of a thing or multiple manifestations of a thing)

1, the manifestation of polymorphism:
Polymorphism is reflected in the code: the parent class reference points to the subclass object
That is, the parent Class A = new subclass ();

2, the premise of polymorphism:
1, there must be a relationship between the class and the class, either inheritance or implementation (the class implements the interface, the interface is equivalent to the parent class, which is the subclass)
2, subclasses want to overwrite the method of the parent class, that is, to have overrides (overwrite). This makes it possible to call the parent class and the subclass with the parent class reference.
Method (that is, the method covered by the subclass), the method in the subclass definition (which overrides the subclass method of the parent class method) is executed (called). Why would
Is there such a phenomenon?
The reason is that the essence of the thing is a subclass object, but this moment, it plays the role of the object of the parent class. It plays as well as possible the parent class, but
After all, he's a subclass, you can take a reference to the parent class and use it as a parent, but you're accessing the contents of the subclass object. Including
Some methods in the parent class are all methods of subclasses.

3. The benefits of polymorphism:
1, greatly improved the extension of the program, making it easy to upgrade the program

4, the disadvantages of polymorphism:
1, when using polymorphism, when referring to a subclass object with a parent class reference, you cannot access a method that is specific to a subclass with a parent class reference. Can only access existing in the parent class
Method.
5. Transformation:
Upward transformation: The upward transformation of the reference variable is done automatically, and when the subclass object is assigned to the parent class reference, the type of the subclass object is converted to the parent class type.
For example: Fu f = new Zi ();
The upward transformation of a variable of a numeric type is also done automatically, for example: byte B = 3; int a = b;

Downward transformation: The downward transformation of the reference variable is mandatory, and the parent class reference to the subclass object can be cast by coercion type, converted by the parent class type to
The subclass type.
For example Zi z = (Zi) f;//Fu f = new Zi ();
The downward transformation of a variable of a numeric type is also mandatory, for example: int a = 3; byte B = (byte) A;

6, the compiler for the transformation of the check:
6.1, for the reference type of downward transformation, the compiler can not judge the right and wrong, can only be judged correctly at run time. Because
A parent class may have more than one child class, and the parent class refers to an object where F might point to subclass a, or to the object of subclass B, as long as
Point to the subclass object, this sentence is not wrong.

F f = new A (); Compile through, because a is a subclass of F

and a parent class reference is cast to subclass type A, or subclass type B, is correct. So this sentence casts
There's nothing wrong with that.
F f = new A ();
b b = (b) F; The compilation passes because F is a reference to the parent class F type, and B is the subclass of F. However, the runtime will
Error, because F is essentially a subclass a object that cannot be turned into a subclass B object, it plays
The object of subclass B, because it does not have some of the methods in subclass B, it can play the parent class F
is because it has all the functions of the parent class and can successfully play the object of the parent class F.

6.2, but for the reference type of the upward transformation, the compiler can check out the correct or not. The standard is that the subclass type goes to the parent class
Type no problem.

7, the nature of polymorphism is: a class of objects in a variety of existing states to switch between. This object is not changed from start to finish, and the object's external
The type of access, or change, is the state of existence that the object provides externally.

7.1. A vivid example:
A father: Lao Wang, a son: Xiao Wang. "Lao Wang", "Xiao Wang" are all names. But the name
Indicates which is the father, which is the son, the father is a type, represents the old generation, the son is another type, represents
is the next generation. That
The son inherits his father.
Class father
{
void Lecture ()
{
S.O.P (business Administration);
}
}
Class Son extends Father
{
void lectures ()//covers the method "lectures" in the parent class (father)
{
S.O.P (Java programming);
}
void See movie ()
{
S.O.P (see movie);
}
}
Father Lao Wang = new Father ();
Son xiao Wang = new Son ();

At this time, know father's old Lee came, Lao Li old to find Father Lao Wang to lecture, talk business management, father not, son Xiao Wang
At home, at this time, son Xiao Wang make up Father Old King (assign a subclass object to the parent class reference), open the door to see Lao Li,
Lao Li took the Lao Wang (Xiao Wang make-up) went to the classroom, Lao Li let Lao Wang began to lecture it (Lao Li called Lao Wang's
The method of teaching, namely "Lao Wang." (), Lao Wang (son Xiao Wang) on the podium began to lecture, an opening talk is
"Java Programming", why? Because Lao Wang is Xiao Wang plays, Xiao Wang can not speak business administration, Xiao Wang will only speak Java programming,
After Xiao Wang finished speaking, he went home.
At this time, Xiao Li to find Xiao Wang, Xiao Wang has not remover, open the door, Xiao Li said, "Uncle Wang, I look for Xiao Wang to see the film", Lao Wang
(Xiao Wang plays) said, "Wait, I'll call him", Lao Wang in the house began to make up remover (will point to their own subclass object
The parent class reference is cast to the subclass type, assigned to the subclass reference, i.e. "son xiao Wang = (son) Lao Wang;" ), and then come out
Went to the movies with Xiao Li (Xiao Li called Xiao Wang's method of seeing the film, "Xiao Wang. See movie ()").
Why did Lao Wang not go to the movies and let Xiao Li call Lao Wang directly? Can't you see the movie? No way! Because Lao Wang (the parent class) did not
This method, which is unique to the subclass, makes the call an error and the method cannot be found.

There are two different ways to do this:
public void static main (string[] args)
{
Father Lao Wang = new Son ();//Only son at home, son play old king

Lao Li is looking for Lao Wang's lectures (Lao Wang);

Son xiao Wang = (son) Lao Wang; Make-up, son Xiao Wang change back to his son state, do back to his

Xiao Li looks for Xiao Wang to see the movie (Xiao Wang)
}
public static void Lao Li looking for Lao Wang Lecture (Father Lecture person)
{
Lecture person. Lecture ();
}
public static void Xiao Li looks for Xiao Wang to see the movie (The man who saw the film)
{
The man who saw the film. Watch a Movie ();
}


8. Summary:
1. For an object, it corresponds to a class member that can be accessed through an object.
Any name (identifier) must have a type that determines the functionality that the name can provide externally. Name
is a term used by the outside world to use the object (handle, flag), through which the name (which represents the value of a reference variable is the address)
The object can be obtained by using the functionality that the object has, which is provided externally by that name
The function is determined by the type of the name.

Type Name Object
Class reference variable name new Class ();

2. For a class name, a class member that is accessible only if the class name is required.
The name is the class name, which is not only the externally provided appellation (handle, flag), but also the type, thus determining its external
Functions that can be provided. This name allows you to use the functionality provided by that type in this case. The value of the class name is the class in the
The first address in the method area.

Type (name)
Class name


3. For variables of non-reference types, that is, variables corresponding to numeric types
The name must have a type that determines the functionality that the variable can provide externally, and the name is the title of the variable (represented)
, the variable can be used by that name to use the functionality provided by the variable (typically the storage function).

Type name Value
Type variable Name value


4. The names of the above three cases correspond to the following:
The names of three cases are essentially references to the values therein. Where the name appears is equivalent to the name of the
The value of the variable represented is written there. There is a one by one mapping between the name and the value in the code.
So, seeing the variable name corresponds to the value it represents (the data in the memory space) or the memory space.

The name of the


variable is equivalent to the value of the variable when the code executes. This is done in this way:
at compile time, the compiler compiles the variable name into a logical address that is the
first address of the variable's logical address, and allocates the physical address in the stack memory (or method area) when the code is executed, allocating memory, and when the variable
name is used, The first address of the physical address
of the variable is identified by the mapping between the logical address and the physical address (that is, the virtual reality of the address), then the length (size) of the memory address space is determined by the type of the variable (that is, the type before the name), and
the binary data in that memory space is correctly removed. And the values are parsed correctly based on the type of the variable. This completes the
variable name-to-value conversion process, which is the value of the variable, which is the value of the variable that the name represents. Then take the value for the action
to complete the execution of the statement.
Example 1:int a = 3;
int b = a*4; The
now allocates space in memory, stores the binary of the number 3, and when you execute the second sentence, you see that the name (marker) A will take the value 3 of the
variable A and multiply it by 4, and then assign the value to B. The
second sentence corresponds to the assembly statement at least 4:
takes the value in a memory space into CPU register A,
takes 4 out of memory into CPU register B,
Multiplies registers A and B, and puts the result in a
The data in a is then stored in the memory space represented by B.

Example 2:animal a = new Animal ();
A.eat ();
A.age = 3;
Allocates the reference variable a in the stack memory and allocates the object memory in the heap memory. The second sentence, see the name name a will refer to the
The value in variable A, which is the first address of the object in the heap memory, is taken out (the removal process is analyzed as above). Then use the
The value is "." operation, locate the object in heap memory, and then access the Eat () member, so find the object
The member method table in the method area to find the code for the method, execute the function (in the stack memory to open the method's
Space, which is used to store local variables within the method).
When the third sentence is executed, you see that name a takes out its value, that is, the object's first address, through the. Operation, finds the object, and then
The age member is accessed by the type of the member age, combined with the first address of the object, to calculate the age in the heap memory
First address, then find the space, and place 3 in that space. Instant is the age in a.age and the space represented by it.
Value, whose value is originally 0, is now assigned a value of 3.
Example 3:animal.sleep ();

Load the class animal into the in-memory method area, and then take out the value of animal by animal, which is what it represents
The first memory address of the class animal. To "." The operation finds the class animal, accessing the Member Method sleep ().

The value here is essentially the data in a memory space (when values are taken) or a memory space (when assigned).
9, instanceof keyword, is a two-dollar operator, using the method:

Reference variable name instanceof class name

Used to determine whether the reference variable named by the reference variable refers to an object that is an instance of the class represented by a class name
It is used to determine whether the object (instance) to which the reference variable is pointing is (an instance) an object (which can be treated as, as, or turned into) a class.
If yes, returns TRUE, otherwise false is returned.

For example:
Animal a = new Cat ();//upward transformation, automatic. Type promotion
if (a instanceof Cat)//Judge the object that the reference variable a points to is not a Cat class object (instance)
{
Cat C = (cat) A; Downward transformation, forcing, restores the object to its original type.
C.catchmouse (); As a subclass object (Cat class object) to use, call the subclass (cat)
Unique method.
}
if (a instanceof Dog)
{
Dog d = (dog) A;
D.watchhome ();
}
Summary: The so-called transformation refers to the transformation of the type, the role of the transformation of the object, the transformation of the existence of the object state. Another way to use objects
form, or another role, or another form of existence of an object, is to use a subclass object as an ancestor class object

An object that can play many roles (can have many kinds of existence, can have many forms), can
Used as many types of objects, an object can be a cost class, a parent class, a grandparent class, an object of all ancestor classes
To use. The reason you can do this is because the object inherits all ancestor classes, has all the contents of the ancestor class, and a
The first class object has something, it is all, it can perfectly play the ancestor object, perfect as the ancestor object use,
Without any errors.
(one might think that it is not the same as the ancestor class, for the overridden method, they perform
is not the same method, the content of the method is different, so it cannot be used as an object of ancestor class, so thinking is wrong
, because the encapsulation (function) nature of the class itself is to shield the implementation of the method, exposing only the method's
Call the interface, only exposes the function definition, hides the function content, so for the outside world, the subclass object has the same
function definition, you can use a subclass object as you would call an ancestor class object, and you can treat the subclass object as an ancestor class
Object use)

Upward transformation, the reason is automatic conversion, this "auto-conversion" is just a name for everyone to show and down transformation
, there is no "automatic", "Not Automatic", "Force", "No enforcement", which essentially means that you do not need to identify
The target type to be converted because a reference to a subclass
Whether the reference to the parent class is legal, only depends on the assignment number = the type at both ends (value type, variable type
You can determine whether the assignment is correct or not. The value type is a subclass type, the variable type is the parent class type, no problem,
Absolutely right. A subclass object can be used as a parent class object.

Downward transformation, the reason to cast, this "cast" is just a name for everyone to show and upward transformation
The automatic conversion is differentiated. There is no "force", "No Force" "Automatic" "Not automatic", essentially refers to the need to identify the
The target type, because assigning a parent class reference to a subclass reference is legal, only by assigning a value number =
Both ends of the type (value type, variable type) to check, cannot be judged out correctly or not, must be evaluated by looking at the assignment
Whether the object represented by the value type on the right side can be used as an object of the type on the left. It is possible to assign a value that is legal,
Otherwise illegal, error. So cat C = (cat) A; in front of a (cat) is used to let the JVM check the object a points to
Whether it can be used as a cat object, and if so, the assignment succeeds, otherwise an error occurs. and grammar rules have to be added
(CAT) to remind the JVM to check that it has been judged by instanceof and added (cat). A parent class has
More than one subclass determines this.


The new class name ();//The expression returns the first address of the object (that is, the object's handle, the object's reference). This address.
The data type is the type of the object's class. Different interpretations of the same data type.

*/


Abstract class Animal
{
abstract void eat ();
}
Class Cat extends Animal
{
public void eat ()
{
System.out.println ("Eat fish");
}
public void Catchmouse ()
{
System.out.println ("Catch Mouse");
}
}
Class Dog extends Animal
{
public void eat ()
{
System.out.println ("Eat Bones");
}
public void Watchhome ()
{
System.out.println ("housekeeping");
}
}
Class Pig extends Animal
{
public void eat ()
{
System.out.println ("Eat feed");
}
public void Run ()
{
System.out.println ("Pig Run! ");
}
}

Class polymorphism
{
public static void Main (string[] args)
{
Animal a = new Cat ();
Feedanimal (a);
Feedanimal (New Dog ());
Feedanimal (New Pig ());
}
public static void Feedanimal (Animal a)//animal a = new Cat (); Polymorphism use
{
A.eat ();
if (a instanceof Cat)
{
Cat C = (cat) A;
C.catchmouse ();
}
if (a instanceof Dog)
{
Dog d = (dog) A;
D.watchhome ();
}
if (a instanceof Pig)
{
Pig p = (pig) A;
P.run ();
}
}
}

Java Multi-State summary

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.