简体   繁体   中英

What happens when new ClassName() is called..?

I know that in simple words an Object is created. But i will better make it clear it with a scenario,

class A {
    public A(String path){
    }
}

class AB extends A{
    public AB(String path){
      super(path);
    }
}

class B{
    public void foo(){
        AB a = new AB("myPath");
        // now will constructor of class AB will run on another instance of 
        // AB or is there any other way "a" constructed.    
    }
}

I'm asking this because if constructor runs on another instance (in this case AB), then who will give it the String path required (and after all no default constructor is allowed here.)

There is no "another instance" in this code; there's just the one.

new AB("myPath") calls public AB(String path) which in turn calls public A(String path) , all on the same instance.

An instance of AB is-an instance of A , which in turn is-an instance of Object .

The constructor will "run on" a newly created instance of AB. A reference to this instance is returned by the new expression and stored as value of a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM