| |

VerySource

 Forgot password?
 Register
Search
View: 661|Reply: 2

Ask the problem of subclass initialization

[Copy link]

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-1-17 15:00:01
| Show all posts |Read mode
When the child class is instantiated, the parent class and child class are loaded, the variables of the parent class and the child class are initialized, and the constructor methods of the parent class and the child class are called, so that a parent class is instantiated? Then the instantiation ends, the parent object becomes garbage?
I'm not sure, you guys have helped a lot. Thank you.
Reply

Use magic Report

1

Threads

20

Posts

15.00

Credits

Newbie

Rank: 1

Credits
15.00

 China

Post time: 2020-1-22 21:09:02
| Show all posts
This parent class does not have any specific references, it should be garbage.

lz look at this code again

class X
{
    Y b = new Y ();

    X ()
    {
System.out.println ("X");
    }
}

class Y
{
    Y ()
    {
System.out.println ("Y");
    }
}

public class Test extends X
{
    Y y = new Y ();

    Test ()
    {
System.out.println ("Z");
    }

    public static void main (String [] args)
    {
new Test ();
    }
}
Reply

Use magic Report

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

 Author| Post time: 2020-1-23 12:36:01
| Show all posts
Read some previous related articles. Now I understand, haha.
I summarized it:
1. Loading, static initialization. Starting from main (), the loader is started. It searches for the keyword "extends" and loads the relevant classes from bottom to top. Then start static initialization from the root base class.
2.Continue to main ().
3.Instance variables (instance variables) are always initialized before the constructor. If the object is instantiated in main (), then the instance variable is initialized from the root base class and the constructor is executed. Finally, initialize the instance variable to the class where main () is located and execute the constructor.
4.Continue to main ().
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list