A deep understanding of examples of Java object instance generation!
Source: Internet
Author: User
A deep understanding of examples of Java object instance generation! -- Linux general technology-Linux programming and kernel information. The following is a detailed description. The Code is as follows:
Class {
Public int Avar;
Public (){
System. out. println ("AAA ");
DoSomething ();
}
Public void doSomething (){
Avar = 1111;
System. out. println ("A. doSomething ()");
}
}
Public class B extends {
Public int Bvar = 2222;
Public B (){
System. out. println ("BBB ");
DoSomething ();
System. out. println ("Avar =" + Avar );
}
Public void doSomething (){
System. out. println ("Bvar =" + Bvar );
}
Public static void main (String [] args ){
New B ();
}
}
Explanation:
The order is as follows. First, generate B and then convert it to,
Therefore, call the constructor of A to output AAA,
Then call the dosomething method ,!!!
Note: This method of A is overwritten by B,
What you generate is B's object,
So it calls Method B,
Because BVAR does not currently have a value,
So the automatic Initialization is 0,
Then generate the B object,
Initialize the variable BVAR first,
Then call the constructor to output BBB,
Then call the method,
BVAR has been initialized,
Therefore, the output BVAR = 2222,
Because the AVAR variable in object A does not call the dosomething method of object,
Therefore, if the value is 0, 0 is output.
The output is as follows:
AAA
Bvar = 0
BBB
Bvar= 2222
Avar = 0
Note: The initialization order. When the class is inherited, the class is a super class object. When the class is generated, the class is a static variable, then a general variable, and then a constructor is called! After a super-class object is generated, the cost object is generated in the same order! When the method is overwritten, call the method of the current object! Note This.
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