Questions about a class in Java in order of precedence

Source: Internet
Author: User

First, post the code, as follows:

public class Test {
public static void Main (string[] args) {
A a=new B ();
A.A ();
}
}

Class a{
Public A () {
System.out.println ("I am A");
}
static{
System.out.println ("AAAAA");
}
{
System.out.println ("111");
}
public void A () {
System.out.println ("AAA");
}
}

Class B extends a{
Public B () {
System.out.println ("I am B");
}
static{
System.out.println ("bbbbb");
}
{
System.out.println ("222");
}
public void A () {
System.out.println ("BBB");
}
}

The result of this code execution is as follows:

AAAAA
bbbbb
111
I ' am A
222
I ' am B
Bbb

This is a very basic but very error-prone point of knowledge, because in Java classes The code is executed in the following order:

Parent Class A static code block, subclass b static code block, parent Class A non-static code block, parent Class A constructor, subclass b non-static code block, sub-class B constructor

As for the output of the A.A () method, the variable A is a Class A () method covered by the quilt class, the common method of variable a (non-static method), at compile time is consistent with the parent class, the runtime is consistent with the subclass, there is a replication, output: BBB;

If the A () method of the variable A is static, then it exists before the object is established and cannot be replicated by the Class B object after the occurrence, so there is no replication, still output: AAA

Questions about a class in Java in order of precedence

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.